902. 最短编辑距离
作者:
dsf2
,
2021-03-05 05:07:49
,
所有人可见
,
阅读 379
import java.util.*;
class Main {
public static int editDist(String str, String target) {
int n = str.length(), m = target.length();
int[][] dp = new int[n + 1][m + 1];
for (int i = 0; i <= m; i++)
dp[0][i] = i;
for (int i = 0; i <= n; i++)
dp[i][0] = i;
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++) {
char ct = target.charAt(i);
char cs = str.charAt(j);
dp[j + 1][i + 1] = dp[j][i + 1] + 1; // Delete
dp[j + 1][i + 1] = Math.min(dp[j + 1][i + 1], dp[j + 1][i] + 1); // insert
dp[j + 1][i + 1] = Math.min(dp[j + 1][i + 1], dp[j][i] + 1); // replace
if (ct == cs)
dp[j + 1][i + 1] = Math.min(dp[j + 1][i + 1], dp[j][i]); // equals
}
return dp[n][m];
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String strN = sc.next();
int m = sc.nextInt();
String strM = sc.next();
System.out.println(editDist(strN, strM));
return;
}
}