1092. Shortest Common Supersequence

Given two strings str1 and str2, return the shortest string that has both str1 and str2 as subsequences.  If multiple answers exist, you may return any of them.

(A string S is a subsequence of string T if deleting some number of characters from T (possibly 0, and the characters are chosen anywherefrom T) results in the string S.)

 

Example 1:

Input: str1 = "abac", str2 = "cab"
Output: "cabac"
Explanation: 
str1 = "abac" is a substring of "cabac" because we can delete the first "c".
str2 = "cab" is a substring of "cabac" because we can delete the last "ac".
The answer provided is the shortest such string that satisfies these properties.

 

Note:

  1. 1 <= str1.length, str2.length <= 1000
  2. str1 and str2 consist of lowercase English letters.

Thinking: superSeq is shortest longest commonSeq binding remaining portion, backtrack to the DP process, the LCS good backtrack relatively simple, direct dp backtrack obtained like array,

2 each string it is divided into two parts: the part of LCS is not part of the LCS, and then merge the like

class Solution(object):
    def shortestCommonSupersequence(self, str1, str2):
        """
        :type str1: str
        :type str2: str
        :rtype: str
        """
        n,m=len(str1),len(str2)
        dp=[[0 for _ in range(m)] for _ in range(n)]
        for i in range(n):
            if str1[i]==str2[0]: 
                for k in range(i,n): dp[k][0]=1
                break
        for j in range(m):
            if str1[0]==str2[j]: 
                for k in range(j,m): dp[0][k]=1
                break
        for i in range(1,n):
            for j in range(1,m):
                if str1[i]==str2[j]:
                    dp[i][j]=dp[i-1][j-1]+1
                else:
                    dp[i][j]=max(dp[i-1][j],dp[i][j-1])
        
        lcs=dp[-1][-1]
        common=[]
        not_common=[]
        p,q=n-1,m-1
        bp,bq=-1,-1
        for i in range(lcs,0,-1):
            bp,bq=p,q
            while p-1>=0 and dp[p-1][q]==i: p-=1
            while q-1>=0 and dp[p][q-1]==i: q-=1
            common.append(str1[p])
            not_common.append((str1[p+1:bp+1],str2[q+1:bq+1]))
            p-=1
            q-=1
        not_common.append([str1[:p+1],str2[:q+1]])

        res=not_common[-1]
        for nc,c in zip(not_common[:-1][::-1],common[::-1]):
            res.append(c)
            res+=nc
        return ''.join(res)
        
        
s=Solution()
print(s.shortestCommonSupersequence(str1 = "abac", str2 = "cab"))
print(s.shortestCommonSupersequence(str1 = "babbbbaa", str2 = "baabbbbba"))
        

 

Guess you like

Origin blog.csdn.net/zjucor/article/details/92384325