Skip to content

Commit e92ee9f

Browse files
authored
Create shortest-common-supersequence.py
1 parent 8a632df commit e92ee9f

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# Time: O(m * n)
2+
# Space: O(m * n)
3+
4+
class Solution(object):
5+
def shortestCommonSupersequence(self, str1, str2):
6+
"""
7+
:type str1: str
8+
:type str2: str
9+
:rtype: str
10+
"""
11+
dp = [[0 for _ in xrange(len(str2)+1)] for _ in xrange(2)]
12+
bt = [[None for _ in xrange(len(str2)+1)] for _ in xrange(len(str1)+1)]
13+
for i, c in enumerate(str1):
14+
bt[i+1][0] = (i, 0, c)
15+
for j, c in enumerate(str2):
16+
bt[0][j+1] = (0, j, c)
17+
for i in xrange(len(str1)):
18+
for j in xrange(len(str2)):
19+
if dp[i % 2][j+1] > dp[(i+1) % 2][j]:
20+
dp[(i+1) % 2][j+1] = dp[i % 2][j+1]
21+
bt[i+1][j+1] = (i, j+1, str1[i])
22+
else:
23+
dp[(i+1) % 2][j+1] = dp[(i+1) % 2][j]
24+
bt[i+1][j+1] = (i+1, j, str2[j])
25+
if str1[i] != str2[j]:
26+
continue
27+
if dp[i % 2][j]+1 > dp[(i+1) % 2][j+1]:
28+
dp[(i+1) % 2][j+1] = dp[i % 2][j]+1
29+
bt[i+1][j+1] = (i, j, str1[i])
30+
31+
i, j = len(str1), len(str2)
32+
result = []
33+
while i != 0 or j != 0:
34+
i, j, c = bt[i][j]
35+
result.append(c)
36+
result.reverse()
37+
return "".join(result)

0 commit comments

Comments
 (0)