两个字符串的删除操作
leetcode:583. 两个字符串的删除操作
动态规划
思路
- 先求最长子序长度
- 然后计算两个原字符串离最长子序长度差多少。
代码实现
class Solution {
public:
/*
(之前搞错了)最长子序长度
word[0:i-1]和word2[0:j-1]的最长子序长dp[i][j]
if(word1[i-1] == word2[j-1]) dp[i][j] = dp[i-1][j-1] + 1;
else dp[i][j] = max(dp[i-1][j],dp[i][j-1]);
初始化为0
*/
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++){
for(int j = 1;j <= word2.size();j++){
if(word1[i-1] == word2[j-1]) dp[i][j] = dp[i-1][j-1] + 1;
else dp[i][j] = max(dp[i-1][j],dp[i][j-1]);
cout<<dp[i][j]<<' ';
}
cout<<endl;
}
return word1.size()+word2.size()-2*dp[word1.size()][word2.size()];
}
};
编辑距离
leetcode:72. 编辑距离
动态规划
思路
增、删、替这三个操作在两个字符串之间是互逆的:
- 增、删是等效的(一个字符串增就是另一个字符串删);而替换就是
dp[i-1][j-1] + 1
代码实现
class Solution {
public:
// word1[0:i-1]和word2[0:j-1]两个字符串相互转化的最少操作数为dp[i][j]
int minDistance(string word1, string word2) {
vector<vector<int>> dp(word1.size()+1,vector<int>(word2.size()+1,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 = 0;i <= word1.size();i++){
for(int j = 0;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,min(dp[i][j-1]+1,dp[i-1][j-1]+1));
// cout<<dp[i][j]<<' ';
}
// cout<<endl;
}
return dp[word1.size()][word2.size()];
}
};
标签:string,55,60,int,word1,word2,字符串,dp
From: https://www.cnblogs.com/tazdingo/p/18102136