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

这题有点东西,可以用两种方法做。

第一种类似edit distance。

初始化第一行第一列还是 0,1,2,3,4。。。。

if word1[i-1]==word2[j-1],那么mem[i][j]=mem[i-1][j-1]

 然后取mem[i-1][j]+2,mem[i][j-1]+1,还有mem[i-1][j-1]+1最小值。

class Solution(object):
    def minDistance(self, word1, word2):
        """
        :type word1: str
        :type word2: str
        :rtype: int
        """
        # Method one, 直接dp,参考edit distance的方法
        mem=[[0 for _ in range(len(word1)+1)] for _ in range(len(word2)+1)]
        for i in range(len(mem)):
            mem[i][0]=i
        for j in range(len(mem[0])):
            mem[0][j]=j
        for i in range(1,len(mem)):
            for j in range(1,len(mem[0])):
                if word2[i-1]==word1[j-1]:
                    mem[i][j]=mem[i-1][j-1]
                else:
                    mem[i][j]=min(mem[i-1][j-1]+2,mem[i-1][j]+1,mem[i][j-1]+1)
        return mem[-1][-1]

第二种方法是,most common subsequence,

还是dp,

初始状态第一行,第一列都是0

if word1[i-1]==word2[j-1], then mem[i][j]=mem[i-1][j-1]

否则,mem[i][j]=max(mem[i-1][j],mem[i][j-1],mem[i][j])

最后返回mem[-1][-1]

class Solution(object):
    def minDistance(self, word1, word2):
        """
        :type word1: str
        :type word2: str
        :rtype: int
        """
        re=self.helper(word1,word2)
        return len(word1)-re+len(word2)-re
    
    
    
    def helper(self,word1,word2):
        mem=[[0 for _ in range(len(word2)+1)] for _ in range(len(word1)+1)]
        re=0
        for i in range(1,len(mem)):
            for j in range(1,len(mem[0])):
                if word1[i-1]==word2[j-1]:
                    mem[i][j]=mem[i-1][j-1]+1
                else:
                    mem[i][j]=max(mem[i-1][j],mem[i][j-1],mem[i-1][j-1])
                re=max(re,mem[i][j])
        return re

 

 

你可能感兴趣的:(LeetCode重点题)