Given two words word1 and word2, find the minimum number of steps required to make word1 and word2 the same, where in each step you can delete one character in either string.

Example 1:

Input: "sea", "eat"
Output: 2
Explanation: You need one step to make "sea" to "ea" and another step to make "eat" to "ea".

Note:

  1. The length of given words won't exceed 500.
  2. Characters in given words can only be lower-case letters.

这道题给了我们两个单词,问我们最少需要多少步可以让两个单词相等,每一步我们可以在任意一个单词中删掉一个字符。那么我们分析怎么能让步数最少呢,是不是知道两个单词最长的相同子序列的长度,并乘以2,被两个单词的长度之和减,就是最少步数了。其实这道题就转换成求Longest Common Subsequence最长相同子序列的问题,令博主意外的是,LeetCode中竟然没有这道题,这与包含万物的LeetCode的作风不符啊。不过没事,有这道题也行啊,对于这种玩字符串,并且是求极值的问题,十有八九都是用dp来解的,曾经有网友问博主,如何确定什么时候用greedy,什么时候用dp?其实博主也不不太清楚,感觉dp要更tricky一些,而且出现的概率大,所以博主一般会先考虑dp,如果实在想不出递推公式,那么就想想greedy能做不。如果有大神知道更好的区分方法,请一定留言告知博主啊,多谢!那么决定了用dp来做,就定义一个二维的dp数组,其中dp[i][j]表示word1的前i个字符和word2的前j个字符组成的两个单词的最长公共子序列的长度。下面来看递推式dp[i][j]怎么求,首先来考虑dp[i][j]和dp[i-1][j-1]之间的关系,我们可以发现,如果当前的两个字符相等,那么dp[i][j] = dp[i-1][j-1] + 1,这不难理解吧,因为最长相同子序列又多了一个相同的字符,所以长度加1。由于我们dp数组的大小定义的是(n1+1) x (n2+1),所以我们比较的是word1[i-1]和word2[j-1]。那么我们想如果这两个字符不相等呢,难道我们直接将dp[i-1][j-1]赋值给dp[i][j]吗,当然不是,我们还要错位相比嘛,比如就拿题目中的例子来说,"sea"和"eat",当我们比较第一个字符,发现's'和'e'不相等,下一步就要错位比较啊,比较sea中第一个's'和eat中的'a',sea中的'e'跟eat中的第一个'e'相比,这样我们的dp[i][j]就要取dp[i-1][j]跟dp[i][j-1]中的较大值了,最后我们求出了最大共同子序列的长度,就能直接算出最小步数了,参见代码如下:

解法一:

class Solution {
public:
int minDistance(string word1, string word2) {
int n1 = word1.size(), n2 = word2.size();
vector<vector<int>> dp(n1 + , vector<int>(n2 + , ));
for (int i = ; i <= n1; ++i) {
for (int j = ; j <= n2; ++j) {
if (word1[i - ] == word2[j - ]) {
dp[i][j] = dp[i - ][j - ] + ;
} else {
dp[i][j] = max(dp[i - ][j], dp[i][j - ]);
}
}
}
return n1 + n2 - * dp[n1][n2];
}
};

下面这种方法也是用的dp,但是和上面的dp思路不太一样,这种算法是跟之前那道Edit Distance相同的思路。那道题问我们一个单词通过多少步修改可以得到另一个单词,其实word2删除一个字符,和跟在word1对应的地方加上那个要删除的字符,达到的效果是一样的,并不影响最终的步骤数,所以这道题完全可以按照那道题的解法来做,一点都不需要变动,定义一个二维的dp数组,其中dp[i][j]表示word1的前i个字符和word2的前j个字符组成的两个单词,能使其变相同的最小的步数,讲解可以参看那篇帖子,参见代码入下:

解法二:

class Solution {
public:
int minDistance(string word1, string word2) {
int n1 = word1.size(), n2 = word2.size();
vector<vector<int>> dp(n1 + , vector<int>(n2 + , ));
for (int i = ; i <= n1; ++i) dp[i][] = i;
for (int j = ; j <= n2; ++j) dp[][j] = j;
for (int i = ; i <= n1; ++i) {
for (int j = ; j <= n2; ++j) {
if (word1[i - ] == word2[j - ]) {
dp[i][j] = dp[i - ][j - ];
} else {
dp[i][j] = + min(dp[i - ][j], dp[i][j - ]);
}
}
}
return dp[n1][n2];
}
};

下面这种方法是解法二的递归写法,用的优化的dfs的方法,用memo数组来保存中间计算结果,以避免大量的重复计算,参见代码如下:

解法三:

class Solution {
public:
int minDistance(string word1, string word2) {
int n1 = word1.size(), n2 = word2.size();
vector<vector<int>> memo(n1 + , vector<int>(n2 + , ));
return helper(word1, word2, , , memo);
}
int helper(string word1, string word2, int p1, int p2, vector<vector<int>>& memo) {
if (memo[p1][p2] != ) return memo[p1][p2];
int n1 = word1.size(), n2 = word2.size();
if (p1 == n1 || p2 == n2) return n1 - p1 + n2 - p2;
if (word1[p1] == word2[p2]) {
memo[p1][p2] = helper(word1, word2, p1 + , p2 + , memo);
} else {
memo[p1][p2] = + min(helper(word1, word2, p1 + , p2, memo), helper(word1, word2, p1, p2 + , memo));
}
return memo[p1][p2];
}
};

类似题目:

Edit Distance

Minimum ASCII Delete Sum for Two Strings

参考资料:

https://discuss.leetcode.com/topic/89285/java-dp-solution-longest-common-subsequence

https://discuss.leetcode.com/topic/89308/dynamic-programming-and-memoization-solution

https://discuss.leetcode.com/topic/89433/two-pointers-recursive-java-solution-with-memoization

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Delete Operation for Two Strings 两个字符串的删除操作的更多相关文章

  1. [LeetCode] 583. Delete Operation for Two Strings 两个字符串的删除操作

    Given two words word1 and word2, find the minimum number of steps required to make word1 and word2 t ...

  2. [LeetCode] 712. Minimum ASCII Delete Sum for Two Strings 两个字符串的最小ASCII删除和

    Given two strings s1, s2, find the lowest ASCII sum of deleted characters to make two strings equal. ...

  3. Leetcode 583.两个字符串的删除操作

    两个字符串的删除操作 给定两个单词 word1 和 word2,找到使得 word1 和 word2 相同所需的最小步数,每步可以删除任意一个字符串中的一个字符. 示例 1: 输入: "se ...

  4. Java实现 LeetCode 583 两个字符串的删除操作(求最长公共子序列问题)

    583. 两个字符串的删除操作 给定两个单词 word1 和 word2,找到使得 word1 和 word2 相同所需的最小步数,每步可以删除任意一个字符串中的一个字符. 示例: 输入: " ...

  5. [LeetCode] Minimum ASCII Delete Sum for Two Strings 两个字符串的最小ASCII删除和

    Given two strings s1, s2, find the lowest ASCII sum of deleted characters to make two strings equal. ...

  6. LeetCode Delete Operation for Two Strings

    原题链接在这里:https://leetcode.com/problems/delete-operation-for-two-strings/description/ 题目: Given two wo ...

  7. [Swift]LeetCode583. 两个字符串的删除操作 | Delete Operation for Two Strings

    Given two words word1 and word2, find the minimum number of steps required to make word1 and word2 t ...

  8. 【Leetcode】583. Delete Operation for Two Strings

    583. Delete Operation for Two Strings Given two words word1 and word2, find the minimum number of st ...

  9. LC 583. Delete Operation for Two Strings

    Given two words word1 and word2, find the minimum number of steps required to make word1 and word2 t ...

随机推荐

  1. Django—urls系统:urls基础

    Django的urls系统简介 Django 1.11版本 URLConf官方文档 URL配置(URLconf)就像Django 所支撑网站的目录.它的本质是URL与要为该URL调用的视图函数之间的映 ...

  2. 网易云音乐APP分析

    网易云音乐-感受音乐的力量 你选择的产品是?  网易云音乐 为什么选择该产品作为分析? 之前用的一直是QQ音乐,但是有一天一个朋友分享了一首网易云上的音乐(顺便分享一下歌名:Drop By Drop) ...

  3. c语言函数作业

    一.PTA实验作业 6-3 使用函数判断完全平方数 1. 本题PTA提交列表 2. 设计思路 1.利用由题目给定的int IsSquare( int n )进行操作 2.首先判断n是否大于0. 3.若 ...

  4. C语言-第一次作业

    题目6-1 计算两数的和与差 1.设计思路 (1)主要描述题目算法 第一步:看主函数知道程序输入浮点型变量a,b,通过函数计算输出和与差. 第二步:函数部分将a赋值op1,b赋值op2,&su ...

  5. 201621123031 《Java程序设计》第8周学习总结

    作业08-集合 1.本周学习总结 以你喜欢的方式(思维导图或其他)归纳总结集合相关内容. 2.书面作业 1. ArrayList代码分析 1.1 解释ArrayList的contains源代码 源代码 ...

  6. memmove 和 memcpy的区别以及处理内存重叠问题

    区别: memcpy和memmove()都是C语言中的库函数,在头文件string.h中,作用是拷贝一定长度的内存的内容,原型分别如下: void *memcpy(void *dst, const v ...

  7. RxSwift(一)

    文/iOS_Deve(简书作者) 原文链接:http://www.jianshu.com/p/429b5160611f 著作权归作者所有,转载请联系作者获得授权,并标注"简书作者" ...

  8. css变化代码

    <!DOCTYPE html><html>    <head>        <meta charset="UTF-8">      ...

  9. 深入浅出 SSL 管理配置实战

    我们生活在一个信息大爆炸的时代,几乎每天都在和互联网打交道,购物.网银转账.支付宝付款.搜索信息.查看邮件.观看视频.微信聊天.上网冲浪.阅读新闻等,无不时时刻刻在和网络打交道.那如何保护网络安全就相 ...

  10. Python机器学习—导入各种数据的N种办法

    pandas 读取数据 一.导入一般的文件 1.read_csv(),用来读取CSV文件 官方文档是这么说的:Read CSV (comma-separated) file into DataFram ...