forked from Answeror/lit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlcs.py
33 lines (27 loc) · 928 Bytes
/
lcs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def lcs(x, y):
n = len(x)
m = len(y)
table = dict() # a hashtable, but we'll use it as a 2D array here
for i in range(n+1): # i=0,1,...,n
for j in range(m+1): # j=0,1,...,m
if i == 0 or j == 0:
table[i, j] = 0
elif x[i-1] == y[j-1]:
table[i, j] = table[i-1, j-1] + 1
else:
table[i, j] = max(table[i-1, j], table[i, j-1])
# Now, table[n, m] is the length of LCS of x and y.
# Let's go one step further and reconstruct
# the actual sequence from DP table:
def recon(i, j):
if i == 0 or j == 0:
return []
elif x[i-1] == y[j-1]:
return recon(i-1, j-1) + [x[i-1]]
elif table[i-1, j] > table[i, j-1]:
return recon(i-1, j)
else:
return recon(i, j-1)
return recon(n, m)