给你两个单词 word1 和 word2, 请返回将 word1 转换成 word2 所使用的最少操作数 。
你可以对一个单词进行如下三种操作:
插入一个字符
删除一个字符
替换一个字符
示例 1:
输入:word1 = "horse", word2 = "ros"
输出:3
解释:
horse -> rorse (将 'h' 替换为 'r')
rorse -> rose (删除 'r')
rose -> ros (删除 'e')
> 动态规划
class Solution {
public:
int minDistance(string word1, string word2) {
int len1 = word1.size();
int len2 = word2.size();
vector<vector<int>> dp(len2 + 1, vector<int>(len1 + 1, 0));
for (int i = 0; i <= len2; i++) dp[i][0] = i;
for (int i = 0; i <= len1; i++) dp[0][i] = i;
for (int i = 1; i <= len2; i++) {
for (int j = 1; j <= len1; j++) {
if (word2[i - 1] == word1[j - 1]) {
dp[i][j] = dp[i - 1][j - 1];
}
else {
dp[i][j] = min({dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]}) + 1;
}
/*cout << i << j << dp[i][j] << endl;*/
}
}
return dp[len2][len1];
}
};
标签:字符,int,距离,编辑,len1,word1,72,word2,rorse
From: https://www.cnblogs.com/lihaoxiang/p/17463053.html