@@ -15,11 +15,68 @@ def lcs(substr1: str, substr2: str) -> int:
1515 return 1 + lcs (substr1 [:- 1 ], substr2 [:- 1 ])
1616 return 0
1717
18+ def print_lcs (substr1 : str , substr2 : str ) -> str :
19+ table = []
20+ # initialize table
21+ for _ in substr1 + " " :
22+ table_row = []
23+ for __ in substr2 + " " :
24+ table_row .append (0 )
25+ table .append (table_row )
26+ table_row = []
27+
28+ for i in range (1 , len (substr1 ) + 1 ):
29+ for j in range (1 , len (substr2 ) + 1 ):
30+ if substr2 [j - 1 ] == substr1 [i - 1 ]: ## if both characters match
31+ table [i ][j ] = table [i - 1 ][j - 1 ] + 1 ## characters match, set the diagonal cell to the curr value + 1
32+ else :
33+ table [i ][j ] = max (table [i - 1 ][j ], table [i ][j - 1 ]) ## either up or left in the lookup table
34+ ## start at bottom right, and follow the path, taking a diagonal left with the letters are the same
35+
36+ startCol = len (table [len (table ) - 1 ]) - 1
37+ startRow = len (table ) - 1
38+
39+ _substr1 = " " + substr1
40+ _substr2 = " " + substr2
41+ substr = ''
42+ pprint (table )
43+ while startCol != 0 and startRow != 0 :
44+ if _substr1 [startRow ] == _substr2 [startCol ]:
45+ ## jump diagonal, add letter
46+ substr += _substr1 [startRow ]
47+ startRow -= 1
48+ startCol -= 1
49+ else :
50+ ## evaluate left
51+ left_ = - 1
52+ if startCol > 0 :
53+ left_ = table [startRow ][startCol - 1 ]
54+ ## evaluate top
55+ top_ = - 1
56+ if startRow > 0 :
57+ top_ = table [startRow - 1 ][startCol ]
58+
59+ if left_ == top_ :
60+ startCol -= 1
61+ if left_ != - 1 and top_ != - 1 :
62+ startRow -= 1 if top_ > left_ else 0
63+ startCol -= 1 if left_ > top_ else 0
64+ if left_ == - 1 :
65+ ## move up
66+ startRow -= 1
67+ if top_ == - 1 :
68+ startCol -= 1
69+ return substr [::- 1 ]
70+
71+
1872
1973if __name__ == '__main__' :
2074 x = 'abcbdab'
2175 y = 'bdcaba'
2276 print (lcs (x , y ))
77+ x2 = 'xmjyauzadfsf'
78+ y2 = 'mzjawxuwqrwe'
79+ print (print_lcs (x2 , y2 ))
2380
2481
2582
0 commit comments