[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)
原创粉丝点击