问题描述
解题思路
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] + 1;
- 删除
word1
的第i
个字符:dp[i][j] = dp[i - 1][j] + 1;
- 删除
word2
的第j
个字符,即相当于在第i
个字符后插入word2[j - 1]
:dp[i][j] = dp[i][j - 1]
- 替换末尾字符:
代码
class Solution {
public:
int minDistance(string word1, string word2) {
vector<vector<int>> dp(word1.size() + 1, vector<int>(word2.size() + 1, 0));
for (int i = 1; i <= word1.size(); i++) {
dp[i][0] = i;
}
for (int j = 1; j <= word2.size(); j++) {
dp[0][j] = j;
}
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(min(dp[i - 1][j - 1], dp[i][j - 1]), dp[i - 1][j]) + 1;
}
}
}
return dp[word1.size()][word2.size()];
}
};
标签:distance,个字符,edit,int,word1,72,word2,dp
From: https://www.cnblogs.com/zwyyy456/p/16841707.html