[LeetCode]Delete Operation for Two Strings

题目描述:

LeetCode 583. Delete Operation for Two Strings

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".

Note:

  1. The length of given words won't exceed 500.
  2. Characters in given words can only be lower-case letters.

题目大意:

给定单词word1和word2,从word1和/或word2中删去一些字符,使得word1和word2相同,求最少删除的字符数。

注意:

  1. 单词长度不超过500
  2. 单词只包含小写字母

解题思路:

解法I 最长公共子序列(Longest Common Subsequence)

求word1和word2的LCS

ans = len(word1) + len(word2) - 2 * len(LCS)

Python代码:

class Solution(object):
    def minDistance(self, word1, word2):
        """
        :type word1: str
        :type word2: str
        :rtype: int
        """
        return len(word1) + len(word2) - 2 * self.lcs(word1, word2)

    def lcs(self, word1, word2):
        len1, len2 = len(word1), len(word2)
        dp = [[0] * (len2 + 1) for x in range(len1 + 1)]
        for x in range(len1):
            for y in range(len2):
                dp[x + 1][y + 1] = max(dp[x][y + 1], dp[x + 1][y])
                if word1[x] == word2[y]:
                    dp[x + 1][y + 1] = dp[x][y] + 1
        return dp[len1][len2]

解法II 动态规划(Dynamic Programming)

状态转移方程:

dp[x][y] = x + y     if x == 0 or y == 0

dp[x][y] = dp[x - 1][y - 1]     if word1[x] == word2[y]

dp[x][y] = min(dp[x - 1][y], dp[x][y - 1]) + 1     otherwise

Python代码:

class Solution(object):
    def minDistance(self, word1, word2):
        """
        :type word1: str
        :type word2: str
        :rtype: int
        """
        len1, len2 = len(word1), len(word2)
        dp = [[0] * (len2 + 1) for x in range(len1 + 1)]
        for x in range(len1 + 1):
            for y in range(len2 + 1):
                if x == 0 or y == 0:
                    dp[x][y] = x + y
                elif word1[x - 1] == word2[y - 1]:
                    dp[x][y] = dp[x - 1][y - 1]
                else:
                    dp[x][y] = min(dp[x - 1][y], dp[x][y - 1]) + 1
        return dp[len1][len2]

 

本文链接:http://bookshadow.com/weblog/2017/05/15/leetcode-delete-operation-for-two-strings/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码

Pingbacks已关闭。

暂无评论

张贴您的评论