LeetCode刷题记138
72. 编辑距离
class Solution {
public int minDistance(String word1, String word2) {
if (word2 == null || word2.length() == 0) return word1.length();
if (word1 == null || word1.length() == 0) return word2.length();
int[][] d = new int[word1.length()][word2.length()];
if (word1.charAt(0) != word2.charAt(0)) d[0][0] = 1;
for (int i = 1; i < word1.length(); i ++) {
if (word1.charAt(i) == word2.charAt(0)) d[i][0] = i;
else d[i][0] = d[i - 1][0] + 1;
}
for (int i = 1; i < word2.length(); i ++) {
if (word1.charAt(0) == word2.charAt(i)) d[0][i] = i;
else d[0][i] = d[0][i - 1] + 1;
}
for (int i = 1; i < word1.length(); i ++) {
for (int j = 1; j < word2.length(); j ++) {
d[i][j] = d[i - 1][j - 1];
if (word1.charAt(i) != word2.charAt(j)) d[i][j] ++;
d[i][j] = Math.min(d[i][j], Math.min(d[i - 1][j], d[i][j - 1]) + 1);
}
}
return d[word1.length() - 1][word2.length() - 1];
}
}
2/3
138/150