AcWing 902. 最短编辑距离-java
原题链接
简单
作者:
Astarion
,
2021-02-19 22:02:33
,
所有人可见
,
阅读 189
import java.io.*;
class Main {
public static void main(String[] args) throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(isr);
int n = Integer.parseInt(in.readLine().trim());
char[] a = in.readLine().toCharArray();
int m = Integer.parseInt(in.readLine().trim());
char[] b = in.readLine().toCharArray();
in.close();
isr.close();
OutputStreamWriter osw = new OutputStreamWriter(System.out);
BufferedWriter out = new BufferedWriter(osw);
int[][] f = new int[n+1][m+1];
//关键:初始化f,从零到长度为i的序列需要操作i次;从长度为i变为长度为0也需操作i次
for (int i = 1; i <= n; i++) f[i][0] = i;
for (int j = 1; j <= m; j++) f[0][j] = j;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++) {
f[i][j] = Math.min(f[i-1][j], f[i][j-1]) + 1;
if (a[i - 1] != b[j - 1]) f[i][j] = Math.min(f[i][j], f[i-1][j-1]+1);
//易错点:遗漏不操作的情况
else f[i][j] = Math.min(f[i][j], f[i-1][j-1]);
}
out.write(f[n][m]+"");
out.flush();
out.close();
osw.close();
}
}