题目描述
给你两个单词 word1 和 word2, 请返回将 word1 转换成 word2 所使用的最少操作数 。
你可以对一个单词进行如下三种操作:
插入一个字符
删除一个字符
替换一个字符
解题思想
删除:dp[i][j] = dp[i-1][j]+1
增加:对word1增加一个,可以对应为把word2删除一个 dp[i][j] = dp[i][j-1]+1
替换:dp[i][j] = dp[i-1][j-1]+1;
代码
/*
dp[i][j]:以i-1为结尾的word1和以j-1为结尾的word2,使其相同的最少操作次数为dp[i][j]
递推公式:
if(word1[i-1] == word2[j-1]) dp[i][j] = dp[i-1][j-1]
else {
//删除:dp[i][j] = dp[i-1][j]+1
//增加:对word1增加一个,可以对应为把word2删除一个 dp[i][j] = dp[i][j-1]+1
//替换:dp[i][j] = dp[i-1][j-1]+1;
dp[i][j] = min(dp[i-1][j],dp[i][j-1],dp[i-1][j-1])+1;
}
初始化:
dp[i][0] = i
dp[0][j] = j
遍历顺序
for(int i=1;i<=word1.size();i++)
for(int j =1;j<=word2.size();j++)
*/
class Solution {
public:
int minDistance(string word1, string word2) {
int m = word1.size();
int 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 j = 1; j <= n; j++) dp[0][j] = j;
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], min(dp[i][j - 1], dp[i - 1][j - 1])) + 1;
}
}
return dp[m][n];
}
};