参考:http://blog.csdn.net/feliciafay/article/details/17502919
题意
求word1变成word2的最短编辑距离。(插入、删除、修改都记为一步操作)
题解
使用动态规划解决。dp[i][j] 表示word1子串(0~i-1)变成word2子串(0~j-1)所需的最短编辑距离。
状态转移方程为:
dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1][j] + 1, dp[i][j - 1] + 1) if(word1[i - 1] == word2[j - 1])
dp[i][j] = min(dp[i - 1][j - 1] + 1, dp[i - 1][j] + 1, dp[i][j - 1] + 1) if(word1[i - 1] != word2[j - 1])
代码
class Solution {
public:
int minDistance(string word1, string word2) {
int len1 = word1.length(), len2 = word2.length();
if(len2 == 0 || len1 == 0)
return max(len1, len2);
int dp[len1 + 1][len2 + 1];
for(int i = 0; i <= len1; i++)
dp[i][0] = i;
for(int j = 0; j <= len2; j++)
dp[0][j] = j;
for(int i = 1; i <= len1; i++)
{
for(int j = 1; j <= len2; j++)
{
int curDis;
if(word1[i - 1] == word2[j - 1])
curDis = dp[i - 1][j - 1];
else
curDis = dp[i - 1][j - 1] + 1;
curDis = min(curDis, dp[i - 1][j] + 1); // word1 delete word1[i]
curDis = min(curDis, dp[i][j - 1] + 1); // word1 insert word2[j]
dp[i][j] = curDis;
}
}
return dp[len1][len2];
}
};