forked from tcandzq/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShortestCommonSupersequence.py
More file actions
53 lines (43 loc) · 1.9 KB
/
ShortestCommonSupersequence.py
File metadata and controls
53 lines (43 loc) · 1.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# -*- coding: utf-8 -*-
# @File : ShortestCommonSupersequence.py
# @Date : 2020-09-12
# @Author : tc
"""
题号 1092.最短公共超序列
给出两个字符串 str1 和 str2,返回同时以 str1 和 str2 作为子序列的最短字符串。如果答案不止一个,则可以返回满足条件的任意一个答案。
(如果从字符串 T 中删除一些字符(也可能不删除,并且选出的这些字符可以位于 T 中的 任意位置),可以得到字符串 S,那么 S 就是 T 的子序列)
示例:
输入:str1 = "abac", str2 = "cab"
输出:"cabac"
解释:
str1 = "abac" 是 "cabac" 的一个子串,因为我们可以删去 "cabac" 的第一个 "c"得到 "abac"。
str2 = "cab" 是 "cabac" 的一个子串,因为我们可以删去 "cabac" 末尾的 "ac" 得到 "cab"。
最终我们给出的答案是满足上述属性的最短字符串。
提示:
1 <= str1.length, str2.length <= 1000
str1 和 str2 都由小写英文字母组成。
参考:https://leetcode.com/problems/shortest-common-supersequence/discuss/312710/C%2B%2BPython-Find-the-LCS
"""
class Solution:
def shortestCommonSupersequence(self, str1: str, str2: str) -> str:
def lcs(A, B):
n, m = len(A), len(B)
dp = [["" for _ in range(m + 1)] for _ in range(n + 1)]
for i in range(n):
for j in range(m):
if A[i] == B[j]:
dp[i + 1][j + 1] = dp[i][j] + A[i]
else:
dp[i + 1][j + 1] = max(dp[i + 1][j], dp[i][j + 1], key=len)
return dp[-1][-1]
res, i, j = "", 0, 0
for c in lcs(str1, str2):
while str1[i] != c:
res += str1[i]
i += 1
while str2[j] != c:
res += str2[j]
j += 1
res += c
i, j = i + 1, j + 1
return res + str1[i:] + str2[j:]