一. Edit Distance
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
Difficulty:Hard
TIME:42MIN
解法(动态规划)
刚开始看到这道题,确实一时间没有想到该怎么解,这道题其实和求两个字符串的最长公共子序列类似,动态规划的思想也十分相似,知道了最优子结构,其实这道题也就没什么难度了。
/*
简单来说,就是把插入,删除和替换对应于某种状态,如果dp表示长度为i的子串到长度为j的子串的编辑距离,那么最优子结构表示如下:
如果dp[i - 1] == dp[j - 1],那么dp[i][j] = dp[i-1][j-1];
如果dp[i - 1] != dp[j - 1],那么对应于三种情况:
1) dp[i][j] = dp[i - 1][j - 1] + 1 替换
2) dp[i][j] = dp[i - 1][j] + 1 删除
3) dp[i][j] = dp[i][j - 1] + 1 插入
*/
int minDistance(string word1, string word2) {
vector<vector<int>> dp(word1.size() + 1,vector<int>(word2.size() + 1, 0));
for(int i = 0; i <= word2.size(); i++)
dp[0][i] = i;
for(int i = 0; i <= word1.size(); i++)
dp[i][0] = i;
for(int i = 1; i <= word1.size(); i++) {
for(int j = 1; j <= word2.size(); j++) {
if(word1[i - 1] == word2[j - 1])
dp[i][j] = dp[i - 1][j - 1];
else
dp[i][j] = min(dp[i - 1][j] + 1,min(dp[i - 1][j - 1] + 1, dp[i][j - 1] + 1));
}
}
return dp[word1.size()][word2.size()];
}
代码的时间复杂度为 O(nm) 。