Leetcode583. Delete Operation for Two Strings

 此题是Longest Common Subsequence变体

Given two strings word1 and word2, return the minimum number of steps required to make word1 and word2 the same.

In one step, you can delete exactly one character in either string.

Example 1:

Input: word1 = "sea", word2 = "eat"
Output: 2
Explanation: You need one step to make "sea" to "ea" and another step to make "eat" to "ea".

Example 2:

Input: word1 = "leetcode", word2 = "etco"
Output: 4
class Solution:
    def minDistance(self, word1: str, word2: str) -> int:
        m, n = len(word1), len(word2)
        def longestCommonSubsequence(text1: str, text2: str) -> int:
            m, n = len(text1), len(text2)
            # dp[i][j] 表示 text1[..i] 和 text2[..j] 的最长公共子序列的长度
            dp = [[0] * (n + 1) for _ in range(m + 1)]
            for i in range(m):
                for j in range(n):
                    if text1[i] == text2[j]:
                        # 如果 text1[i] == text2[j] ,则必定选择这两个字符作为最长公共子序列的结尾,
                        # 那么状态 dp[i + 1][j + 1] 可由 dp[i][j] + 1 转移而来
                        dp[i + 1][j + 1] = dp[i][j] + 1
                    else:
                        # 如果 text1[i] != text2[j] ,
                        # 则 dp[i + 1][j + 1] 只能从 dp[i + 1][j] 和 dp[i][j + 1] 直接转移
                        dp[i + 1][j + 1] = max(dp[i + 1][j], dp[i][j + 1])

            # dp[m][n] 就是 text1 和 text2 的最长公共子序列的长度
            return dp[m][n]
        return m + n - 2*longestCommonSubsequence(word1,word2)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值