File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change
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 ))
You can’t perform that action at this time.
0 commit comments