一、583.两个字符串的删除操作
代码如下:
class Solution {
public:
int minDistance(string word1, string word2) {
vector<vector<int>> dp(word1.size() + 1, vector<int>(word2.size() + 1));
for (int i = 0; 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]; // 两个元素相等,两个word中都不用删除了
// 两个元素不相等时,就要考虑删除word1中的,还是word2中的,能够使得相等时操作步数最少(同时删除word1和word2,操作数加2这一句可以省略,因为就是在dp[i - 1][j] + 1或dp[i][j - 1] + 1的基础上删除word1中的元素再加1)
else {
dp[i][j] = min({dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + 2}); // 删除word1中元素,删除word2中元素,同时删除元素 的操作步数
// min三个元素比较:min({ , , })
}
}
}
return dp[word1.size()][word2.size()];
}
};
二、72.编辑距离
代码如下:
class Solution {
public:
int minDistance(string word1, string word2) {
vector<vector<int>> dp(word1.size() + 1, vector<int> (word2.size() + 1));
for (int i = 0; i <= word1.size(); i++) dp[i][0] = i;
for (int j = 0; 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({dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + 1});
// word1删除一个元素;word2删除一个元素;word1中替换word1[i-1],使其与word2[j-1]相同
}
}
}
return dp[word1.size()][word2.size()];
}
};