leetcode583. Delete Operation for Two Strings
来源:互联网 发布:美工提成怎么算 编辑:程序博客网 时间:2024/06/06 04:00
题目
Given two words word1 and word2, find the minimum number of steps required to makeword1 and word2 the same, where in each step you can delete one character in either string.
Example 1:
Input: "sea", "eat"Output: 2Explanation: You need one step to make "sea" to "ea" and another step to make "eat" to "ea".
Note:
- The length of given words won't exceed 500.
- Characters in given words can only be lower-case letters.
思路
要让操作数最少,那么就是说留下的应当是两者的最大公共子序列,那么问题就转换成求LCS长度的问题了。只要先找到两者的最长公共子序列的,然后分别做差求和就行了。LCS的话还是用DP做就好了,并且只要求长度就行了。table[i][j],表示匹配到s1[i],s2[j]时的LCS长度。转换方程s1[i-1]==s2[j-1] :table[i][j] = table[i - 1][j - 1] + 1; s1[i-1]!=s2[j-1] :table[i][j] =max(table[i][j-1], table[i-1][j]);
代码
class Solution {public: int minDistance(string word1, string word2) { int table[501][501]; for (int i = 1; i < word1.length()+1; i ++) { for (int j = 1; j < word2.length()+1; j ++) { if (word1[i - 1] == word2[j - 1]) { table[i][j] = table[i - 1][j - 1] + 1; } else { table[i][j] = max(table[i][j-1], table[i-1][j]); } } } int lcs =table[word1.length()][word2.length()]; return (word1.length() - lcs) + (word2.length() - lcs); }};
阅读全文
0 0
- leetcode583. Delete Operation for Two Strings
- 第十三周:( LeetCode583) Delete Operation for Two Strings(c++)
- Delete Operation for Two Strings
- 583. Delete Operation for Two Strings Medium
- [LeetCode]583. Delete Operation for Two Strings
- 583. Delete Operation for Two Strings
- [leetcode 583] Delete Operation for Two Strings
- [leetcode] 583. Delete Operation for Two Strings
- 583. Delete Operation for Two Strings
- 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
- 583.Delete Operation for Two Strings
- LeetCode:M-583. Delete Operation for Two Strings
- Delete Operation for Two Strings问题及解法
- Leetcode之Delete Operation for Two Strings 问题
- #leetcode编程日记#583. Delete Operation for Two Strings
- 史上最简单的 MySQL 教程(十二)「记录长度」
- EOJ----F. 蚂蚁
- 十、Sqoop简介
- 如何优化Hibernate?
- hibernate关联映射:多对一、一对一
- leetcode583. Delete Operation for Two Strings
- First Unique Character in a String
- UML关系(泛化,实现,依赖,关联(聚合,组合))
- [Android] RecyclerView滑动没有惯性效果
- [系统操作][grub4dos]引导硬盘映像文件
- Openwrt WIFI探针开发【一】
- Invalid character constant
- c++string类型管理
- STL中优先队列(priority_queue)的相关操作