其他分享
首页 > 其他分享> > 1092. Shortest Common Supersequence

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.

思路:最短的superSeq就是最长的commonSeq结合剩余的部分,所以要backtrack DP过程,好在LCS的backtrack还比较简单,直接对得到的dp数组backtrack就好了,

吧2个string每个都分割成2部分:是LCS的部分,不是LCS的部分,然后merge下就好了

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

 

标签:string,1092,str2,str1,range,Supersequence,Shortest,dp,common
来源: https://blog.csdn.net/zjucor/article/details/92384325