1092. Shortest Common Supersequence

87 篇文章 0 订阅

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

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值