Skip to content

Commit

Permalink
Merge pull request #76 from tapumar/patch-1
Browse files Browse the repository at this point in the history
Create LCS.py
  • Loading branch information
srbcheema1 authored Oct 3, 2017
2 parents fce3220 + 33f519b commit 24d6134
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions string/LCS.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
def lcs(a, b):
lengths = [[0 for j in range(len(b)+1)] for i in range(len(a)+1)]

# row 0 and column 0 are initialized to 0 already

for i, x in enumerate(a):
for j, y in enumerate(b):
if x == y:
lengths[i+1][j+1] = lengths[i][j] + 1
else:
lengths[i+1][j+1] = max(lengths[i+1][j], lengths[i][j+1])

# read the substring out from the matrix
result = ""
x, y = len(a), len(b)
while x != 0 and y != 0:
if lengths[x][y] == lengths[x-1][y]:
x -= 1
elif lengths[x][y] == lengths[x][y-1]:
y -= 1
else:
assert a[x-1] == b[y-1]
result = a[x-1] + result
x -= 1
y -= 1
return result

0 comments on commit 24d6134

Please sign in to comment.