编辑距离,学过算法的应该都很熟悉
把一个单词变另一个单词,增删改分别算一次操作
public class Solution {
public int minDistance(String word1, String word2) {
int m = word1.length();
int n = word2.length();
//声明一个二维数组
int[][] cost = new int[m + 1][n + 1];
//初始化行和列
for(int i = 0; i <= m; i++)
cost[i][0] = i;
for(int i = 1; i <= n; i++)
cost[0][i] = i;
//两层for循环
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
//如果相等,从对角线过来,不需要加入操作
if(word1.charAt(i) == word2.charAt(j))
cost[i + 1][j + 1] = cost[i][j];
else {
//否则的话,选最小的边过来
int a = cost[i][j];
int b = cost[i][j + 1];
int c = cost[i + 1][j];
cost[i + 1][j + 1] = a < b ? (a < c ? a : c) : (b < c ? b : c);
cost[i + 1][j + 1]++;
}
}
}
return cost[m][n];
}
}