|
| 1 | +import sys |
| 2 | + |
| 3 | +# 1. Express a solution mathematically: |
| 4 | +# Let's A be a matrix of alignments of (|s| + 1) x (|t| + 1) |
| 5 | +# A[0,0] = 0 |
| 6 | +# A[0,c] = 0 for 1 <= c <= |s| |
| 7 | +# A[r,0] = 0 for 1 <= r <= |t| |
| 8 | +# A[r,c] = max(A[r-1,c-1] + 1 if s[c] = t[r] else 0, A[r-1,c] + 0, A[r,c-1] + 0) for 1 <= c <= |s| and 1 <= r <= |t| |
| 9 | +# 2. Proof: |
| 10 | +# 3. Implementation: buttom up solution |
| 11 | +# Running time: O(nm) |
| 12 | +# Space Complexity: O(nm) |
| 13 | +class Solution: |
| 14 | + def __init__(self, s, t): |
| 15 | + self.rows_count = len(t) + 1 |
| 16 | + self.columns_count = len(s) + 1 |
| 17 | + |
| 18 | + A = self.built_lcs_matrix(s, t) |
| 19 | + self.lcs = self.get_lcs(A) |
| 20 | + |
| 21 | + def built_lcs_matrix(self, s, t): |
| 22 | + A = [ [0 for _ in range(self.columns_count)] for _ in range(self.rows_count)] |
| 23 | + |
| 24 | + for r in range(1, self.rows_count, 1): |
| 25 | + for c in range(1, self.columns_count, 1): |
| 26 | + alignment_score = A[r-1][c-1] + 1 if t[r-1] == s[c-1] else 0 |
| 27 | + delete_score = A[r][c-1] |
| 28 | + insert_score = A[r-1][c] |
| 29 | + A[r][c] = max(alignment_score, delete_score, insert_score) |
| 30 | + |
| 31 | + return A |
| 32 | + |
| 33 | + def get_lcs(self, A): |
| 34 | + lcs_inverse_list = [] |
| 35 | + |
| 36 | + r = self.rows_count - 1 |
| 37 | + c = self.columns_count - 1 |
| 38 | + while r > 0 and c > 0: |
| 39 | + |
| 40 | + if A[r][c] == A[r - 1][c - 1] + 1 and s[c - 1] == t[r - 1]: |
| 41 | + lcs_inverse_list.append(s[c - 1]) |
| 42 | + c = c - 1 |
| 43 | + r = r - 1 |
| 44 | + |
| 45 | + elif A[r][c] == A[r - 1][c - 1]: |
| 46 | + c = c - 1 |
| 47 | + r = r - 1 |
| 48 | + |
| 49 | + elif A[r][c] == A[r][c - 1]: |
| 50 | + c = c - 1 |
| 51 | + |
| 52 | + elif A[r][c] == A[r - 1][c]: |
| 53 | + r = r - 1 |
| 54 | + |
| 55 | + return ''.join(lcs_inverse_list[::-1]) |
| 56 | + |
| 57 | + |
| 58 | +if __name__ == "__main__": |
| 59 | + s,t = sys.stdin.read().strip().splitlines() |
| 60 | + |
| 61 | + lcs_solution = Solution(s,t) |
| 62 | + |
| 63 | + print(lcs_solution.lcs) |
0 commit comments