Edit Distance 原题地址:
https://oj.leetcode.com/problems/edit-distance/
The edit distance of two strings, s1 and s2, is defined as the minimum number of point mutations required to change s1 into s2, where a point mutation is one of:
- change a letter,
- insert a letter or
- delete a letter
计算两个字符串s1+ch1, s2+ch2的编辑距离有这样的性质:
1. d(s1,””) = d(“”,s1) = |s1| d(“ch1”,”ch2”) = ch1 == ch2 ? 0 : 1;
2. d(s1+ch1,s2+ch2) = min(d(s1,s2)+ ch1==ch2 ? 0 : 1 , d(s1+ch1,s2), d(s1,s2+ch2) );
第一个性质是显然的。
第二个性质: 由于我们定义的三个操作来作为编辑距离的一种衡量方法。
于是对ch1,ch2可能的操作只有
1. 把ch1变成ch2
2. s1+ch1后删除ch1 d = (1+d(s1,s2+ch2))
3. s1+ch1后插入ch2 d = (1 + d(s1+ch1,s2))
对于2和3的操作可以等价于:
_2. s2+ch2后添加ch1 d=(1+d(s1,s2+ch2))
_3. s2+ch2后删除ch2 d=(1+d(s1+ch1,s2))
因此可以得到计算编辑距离的性质2。
public class Solution {
public int minDistance(String word1, String word2) {
int len1 = word1.length();
int len2 = word2.length();
if (len1 == 0)
return len2;
if (len2 == 0)
return len1;
int[][] dist = new int[len1+1][len2+1];
for (int i = 0; i <= len1; i++)
dist[i][0] = i;
for (int j = 0; j <= len2; j++)
dist[0][j] = j;
for (int i = 1; i <= len1; i++)
for (int j = 1; j <= len2; j++) {
if (word1.charAt(i-1) == word2.charAt(j-1))
dist[i][j] = dist[i-1][j-1];
else
dist[i][j] = Math.min(Math.min(dist[i-1][j-1] + 1, dist[i-1][j] + 1), dist[i][j-1] + 1);
}
return dist[len1][len2];
}
}