72.编辑距离
给你两个单词 word1 和 word2,请你计算出将 word1 转换成 word2 所使用的最少操作数 。
你可以对一个单词进行如下三种操作:
插入一个字符
删除一个字符
替换一个字符
- 用动态规划的方法
- 使得word1[0]-word1[i]与word2[0]-word2[j]匹配的情况:
- word1[0]-word1[i-1]与word2[0]-word2[j-1]已经匹配且word1[i] == word2[j]
- word1[0]-word1[i-1]与word2[0]-word2[j-1]已经匹配且word1[i] != word2[j]
- word1[0]-word1[i-1]与word2[0]-word2[j]已经匹配
- word1[0]-word1[i]与word2[0]-word2[j-1]已经匹配
对于以上几种情况:
- 不用操作,dp[i][j] = dp[i-1][j-1]
- 将word1[i]替换成word2[j] ,多一步操作,dp[i][j] = dp[i-1][j-1] + 1
- 将word1[i]删除,多一步操作,dp[i][j] = dp[i-1][j] + 1
- 插入word2[j],多一步操作,dp[i][j] = dp[i][j-1] + 1
取以上情况的最小操作数就是结果
class Solution {
public:
int minDistance(string word1, string word2) {
int m = word1.size(),n = word2.size();
vector<vector<int> > dp(m+1,vector<int>(n+1,0));
for(int i = 0;i <= m;i++){
dp[i][0] = i;
}
for(int i = 0;i <= n;i++){
dp[0][i] = i;
}
for(int i = 1;i <= m;i++){
for(int j = 1;j <= n;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][j-1],dp[i-1][j])) + 1;
}
}
}
return dp[m][n];
}
};
通过时间: