public class Solution {
/**
* @param word1 & word2: Two string.
* @return: The minimum number of steps.
*/
public int minDistance(String word1, String word2) {
// 2015-05-20
if (word1 == null || word2 == null) {
return 0;
}
int m = word1.length();
int n = word2.length();
int[][] min = new int[m + 1][n + 1];
for (int i = 0; i <= m; i++) {
min[i][0] = i;
}
for (int j = 1; j <= n; j++) {
min[0][j] = j;
}
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
min[i][j] = min[i - 1][j - 1];
} else {
min[i][j] = Math.min(min[i][j - 1] + 1, min[i - 1][j] + 1);
min[i][j] = Math.min(min[i][j], min[i - 1][j - 1] + 1);
}
}
}
return min[m][n];
}
}
当最后一个字符不同时对应三种情况,举例:
mart ->karma 有三种情况
1. mart -> karm_ + 增
2. mar_ -> karma + 删
3. mar_ -> karm_ + 改