两个字符串的删除操作
给定两个单词 word1 和 word2 ,返回使得 word1 和 word2 相同所需的最小步数。
每步 可以删除任意一个字符串中的一个字符。
示例 1:
输入: word1 = "sea", word2 = "eat"
输出: 2
解释: 第一步将 "sea" 变为 "ea" ,第二步将 "eat "变为 "ea"
示例 2:
输入:word1 = "leetcode", word2 = "etco"
输出:4
提示:
1 <= word1.length, word2.length <= 500
word1 和 word2 只包含小写英文字母
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/delete-operation-for-two-strings
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路:动态规划
最长公共子序列的变式,见注释。
code
class Solution {
public:
//sea
//eat
//删除任意字符相同的最小次数
//删除次数最少之后相同
//也就是删除之后得到的是最长的公共子序列
//ans = word1.size() + word2.size() - 2 * LCS
int minDistance(string word1, string word2) {
int m = word1.size(),n = word2.size();
vector<vector<int>> f(m+1,vector<int>(n+1,0));
for(int i = 1;i <= m;i++)
{
for(int j = 1;j <= n;j ++)
{
if(word1[i-1] == word2[j-1]) f[i][j] = f[i-1][j-1] + 1;
else f[i][j] = max(f[i-1][j],f[i][j-1]);
}
}
int lcs = 0;
for(auto row : f)
for(auto item : row)
lcs = max(lcs,item);
return m + n - 2 * lcs;
}
};