[leetcode 583] Delete Operation for Two Strings
来源:互联网 发布:js关键字直接量 编辑:程序博客网 时间:2024/05/16 12:34
Description:
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”.
这道题其实就是给定两个字符串然后找到最大公共子串。
我的solution是:
从第一个字符开始,如果这个字符对应的dp 不存在,那么它的dp 的计算公式如下:
对于 dp(i, j), 如果 i 或者j 对应的是该字符串的最后一个字符,那么最后的结果就是 len(word1) + len(word2) - i - j
对于word1[i] == word2[j] 的情况,那么也就是说明这两个字符是相同的,他们的最大子串的长度 == dp(i + 1, j + 1)
对于当前比较的两个字符不同的情况,那么他们的找到最大子串的的结果也就是 1 + min(dp(i + 1, j), dp(i, j + 1))
最后贴代码:
class Solution(object): def minDistance(self, word1, word2): common = {} def dp(i , j): if (i, j) not in common: if i == len(word1) or j == len(word2): ans = len(word1) + len(word2) - i - j elif word1[i] == word2[j]: ans = dp(i + 1, j + 1) else: ans = 1 + min(dp(i, j + 1), dp(i + 1, j)) common[i, j] = ans return common[i, j] return dp(0, 0)
阅读全文
0 0
- [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
- 【Leetcode-Medium-583】Delete Operation for Two Strings
- Delete Operation for Two Strings
- LeetCode:M-583. Delete Operation for Two Strings
- Leetcode之Delete Operation for Two Strings 问题
- #leetcode编程日记#583. Delete Operation for Two Strings
- [python]leetcode(72). Edit Distance AND (583). 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
- Linux 输出重定向>和>>的区别
- cocos-js android打包跨越坑
- mysql explain type连接类型示例
- mysql添加外键约束
- jquery ligerUI
- [leetcode 583] Delete Operation for Two Strings
- MobileUI组件
- Proguard说明,android代码混淆
- textarea提交的时候怎么去除首尾的空格
- spring 同时配置hibernate and jdbc 事务
- DelegatingFilterProxy作用浅析
- angular js 上传插件 angular-file-upload 和 ng-file-upload 使用时注意事项
- 短URL系统如何设计方案
- 关于Recyclerview 实现多选,单选,全选,反选,批量删除的功能的实现