[leetcode 583] Delete Operation for Two Strings

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值