Skip to content

Commit f488de1

Browse files
committed
daily
1 parent 13caea8 commit f488de1

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

my-submissions/h1092.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
class Solution:
2+
def shortestCommonSupersequence(self, str1: str, str2: str) -> str:
3+
dp = [[i for i in range(len(str1) + 1)]] + \
4+
[[i] + [None] * len(str1) for i in range(1, 1 + len(str2))]
5+
dp[0][0] = 0
6+
7+
for i, ci in enumerate(str2, 1) :
8+
for j, cj in enumerate(str1, 1) :
9+
dp[i][j] = min(
10+
dp[i - 1][j],
11+
dp[i][j - 1],
12+
dp[i - 1][j - 1] if ci == cj else inf # if same letter
13+
) + 1
14+
15+
output = []
16+
r, c = len(dp) - 1, len(dp[0]) - 1
17+
18+
while r > 0 and c > 0 :
19+
if dp[r][c] == dp[r - 1][c - 1] + 1 and str1[c - 1] == str2[r - 1]:
20+
c -= 1
21+
r -= 1
22+
output.append(str1[c])
23+
continue
24+
25+
if dp[r][c - 1] == dp[r][c] - 1 :
26+
c -= 1
27+
output.append(str1[c])
28+
continue
29+
30+
r -= 1
31+
output.append(str2[r])
32+
33+
output.extend((reversed(str1[:c])))
34+
output.extend((reversed(str2[:r])))
35+
36+
return ''.join(reversed(output))

0 commit comments

Comments
 (0)