【算法题】Leedcode 72. Edit Distance字符串转换步数最优解问题
题目链接: https://leetcode.com/problems/edit-distance/
解法参考: http://www.bubuko.com/infodetail-644271.html
http://blog.sina.com.cn/s/blog_6f611c300101f72q.html
http://blog.csdn.net/feliciafay/article/details/17502919
Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)
You have the following 3 operations permitted on a word:
a) Insert a character
b) Delete a character
c) Replace a character
两个字符串通过插入、删除、替换一个字符的操作变得一样,求最少的步数。
思路:动态规划
解释:
用d[i][j]表示从word1[i]变为word2[j]所需要的最少步骤,word[i] 表示word的0~i的子字符串。
最后第二步到最后一步会有三种情况(4种操作):
1) 匹配(无操作或替换):即word1[i-1] = word2[j-1] , 则如果两个字符串的最后一个字符相同则不需要操作,操作数为d[i-1][j-1]+0;
……不一样则执行替换操作,操作数为d[i-1][j-1]+1.
3) 少一位(插入): 即word1[i] = word2[j-1],则 word1 插入 word2 的最后一个字符,操作数d[i][j-1]+1.
4) 多一位(删除): 即word1[i-1] = word2[j],则 word1 删除最后一个字符,操作数d[i-1][j]+1.
当前步数最优解则为三种情况的最小值: d[i][j]
例如:abca和cba最优解为2步:
# a b c a
# 0 1 2 3 4
c 1 1 2 2 3
b 2 2 1 2 3
a 3 3 2 2 2
代码:
public int minDistance(String word1, String word2) {
int len1 = word1.length();
int len2 = word2.length();
int d[][] = new int[len1 + 1][len2 + 1];
for (int i = 0; i < len1 + 1; i++) {
for (int j = 0; j < len2 + 1; j++) {
if (i * j == 0) {
d[i][j] = i == 0 ? j : i;
} else if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
d[i][j] = d[i - 1][j - 1];
} else {
d[i][j] = min(d[i - 1][j - 1], d[i - 1][j], d[i][j - 1]) + 1;
}
}
}
return d[len1][len2];
}
public int min(int ...is){
int min = is[0];
for (int n: is){
min = min <= n ? min : n;
}
return min;
}
精简版(公式):
public int minDistance(String word1, String word2) {
int len1 = word1.length();
int len2 = word2.length();
int d[][] = new int[len1 + 1][len2 + 1];
for (int i = 0; i < len1 + 1; i++) {
for (int j = 0; j < len2 + 1; j++) {
if (i * j == 0) {
d[i][j] = i == 0 ? j : i;
} else {
d[i][j] = min((word1.charAt(i - 1) == word2.charAt(j - 1) ? d[i - 1][j - 1] : d[i - 1][j - 1] + 1),
d[i - 1][j] + 1, d[i][j - 1] + 1);
}
}
}
return d[len1][len2];
}
另:
其他思路:最大匹配子串、递归处理、范围限制查找等等
参考:
http://blog.csdn.net/sunnyyoona/article/details/43853383
http://blog.unieagle.net/2012/09/19/leetcode%E9%A2%98%E7%9B%AE%EF%BC%9Aedit-distance%EF%BC%8C%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%B9%8B%E9%97%B4%E7%9A%84%E7%BC%96%E8%BE%91%E8%B7%9D%E7%A6%BB%EF%BC%8C%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92/