我看过很多代码来解决这个问题,但我不明白为什么他们使用矩阵来表示两个单词之间的距离。谁能给我解释一下?
这是我找到的示例代码:
public static int minDistance(String word1, String word2)
{
int l1 = word1.length(), l2 = word2.length();
int[][] d = new int[l1 + 1][l2 + 1];
// the edit distance between an empty string and the prefixes of
// word2
for (int i = 0; i < l2 + 1; i++) {
d[0][i] = i;
}
// the edit distance between an empty string and the prefixes of
// word1
for (int j = 0; j < l1 + 1; j++) {
d[j][0] = j;
}
for (int i = 1; i < l1 + 1; i++) {
for (int j = 1; j < l2 + 1; j++) {
if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
d[i][j] = d[i - 1][j - 1];
} else {
d[i][j] = min(1 + d[i][j - 1], 1 + d[i - 1][j],
1 + d[i - 1][j - 1]); // min of insertion,
// deletion, replacement
}
}
}
return d[l1][l2];
}