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