Leetcode之Delete Operation for Two Strings 问题
来源:互联网 发布:西安卧龙网络 编辑:程序博客网 时间:2024/06/05 19:13
问题描述:
Given two words word1 and word2, find the minimum number of steps required to makeword1 andword2 the same, where in each step you candelete one characterin either string.
Note:
- The length of given words won't exceed 500.
- Characters in given words can only be lower-case letters.
示例:
Input: "sea", "eat"Output: 2Explanation: You need one step to make "sea" to "ea" and another step to make "eat" to "ea".
问题来源:Delete Operation for Two Strings(详细地址:https://leetcode.com/problems/delete-operation-for-two-strings/description/)
思路分析:在这,我们先来介绍一下子序列和子串的区别,为了简单起见,我们直接看个例子:
假设字符串为"abcdefg",子序列指的是去掉原字符串的一些字符,得到的一个个字符按照原字符串的先后顺序连起来得到的序列,就是我们说的子序列,比如:{a,c,e,f},{a,d,g},{c,d,e,f,g}。而子串必须是连续的字符串,比如:{b,c,d},{c,d,e,f,g}等等都是子字符串。
这道题我们就需要采用最长公共子序列(lcs问题)来求解了,这道题给的示例有点诱惑性,让人觉得求最长公共子串就得到答案了,但是实际上这道题需要得到最长子序列(题题干给的delete很关键,和子序列的构成过程很像),然后,我们只需要用原来的两个字符串的长度分别减去lcs,最后相加起来就是最终结果了。所以问题转换为求解lcs了,有很多朋友肯定是已经很熟悉的了,我在这还是简单介绍一下吧:
刚开始,我们用两个指针(i和j)分别指向两个字符串,最初,i=0或者j=0的话,显而易见dp[i][j] = 0,因为没有公共子序列嘛,很容易理解;
另外,如果两个数组当前指向的数字是相等的,说明最长公共子序列又要加1了,即dp[i][j] = dp[i - 1][j - 1] + 1;相反,如果它们是不等的,dp[i][j]要么是dp[i - 1][j],要么就是dp[i][j - 1],因为此时的最长公共子序列肯定是其中一个字符串的最末位置和另外一个字符串末位置的前一个位置所构成的,举个例子:假设当前公共子序列为:abcde,这个e必然是来自于其中一个字符串的末位置,dp[i-1][j]的意思就是i和j所指向的字符是不一样的,但是它们的最长公共子序列是由a[i-1]和b[j]构成的,即上一个最长的公共子序列搭配上b[j]这个字符,构成了新的最长公共子序列。同理,dp[i][j-1]也是这个道理。
整理归纳一下:
代码:
主函数:
求解最长公共子长的函数:
- Leetcode之Delete Operation for Two Strings 问题
- [LeetCode]583. Delete Operation for Two Strings
- [leetcode 583] Delete Operation for Two Strings
- [leetcode] 583. Delete Operation for Two Strings
- [leetcode]583. Delete Operation for Two Strings
- leetcode 583. Delete Operation for Two Strings
- [LeetCode] 583. Delete Operation for Two Strings
- Delete Operation for Two Strings
- LeetCode:M-583. Delete Operation for Two Strings
- #leetcode编程日记#583. Delete Operation for Two Strings
- 【Leetcode-Medium-583】Delete Operation for Two Strings
- Delete Operation for Two Strings问题及解法
- 583. Delete Operation for Two Strings Medium
- 583. Delete Operation for Two Strings
- leetcode583. Delete Operation for Two Strings
- 583. Delete Operation for Two Strings
- 583. Delete Operation for Two Strings
- 583.Delete Operation for Two Strings
- Android studio使用svn创建分支及合并分支----终极图解
- Notes of “Fast Bilateral-Space Stereo for Synthetic Defocus”
- mysql中对表的操作
- HDU-2846 Repository (Trie 字典树 入门题)
- Ubuntu 10.10安装与配置jdk
- Leetcode之Delete Operation for Two Strings 问题
- React-Native自学之路(1)
- Python3 (入门6) 库的打包与安装
- Oracle EBS财务模块(三)总账功能
- Js中的window.parent ,window.top,window.self 详解
- spark work ResultTask 源码分析
- oracle 备份
- 解决input获得焦点时边框没有border-radius
- 仿真复现文章推荐