标签:string 1092 str2 str1 range Supersequence Shortest dp common
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 <= str1.length, str2.length <= 1000
str1
andstr2
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
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。