Skip to content

Commit e6d0e2e

Browse files
committed
Added LCS code in Python
1 parent 5103790 commit e6d0e2e

File tree

1 file changed

+22
-0
lines changed
  • DP/LongestCommonSubsequence

1 file changed

+22
-0
lines changed

DP/LongestCommonSubsequence/LCS.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
def lcs(X , Y):
2+
# find the length of the strings
3+
m = len(X)
4+
n = len(Y)
5+
6+
# declaring the array for storing the dp values
7+
L = [[None]*(n+1) for i in xrange(m+1)]
8+
9+
"""Following steps build L[m+1][n+1] in bottom up fashion
10+
Note: L[i][j] contains length of LCS of X[0..i-1]
11+
and Y[0..j-1]"""
12+
for i in range(m+1):
13+
for j in range(n+1):
14+
if i == 0 or j == 0 :
15+
L[i][j] = 0
16+
elif X[i-1] == Y[j-1]:
17+
L[i][j] = L[i-1][j-1]+1
18+
else:
19+
L[i][j] = max(L[i-1][j] , L[i][j-1])
20+
21+
# L[m][n] contains the length of LCS of X[0..n-1] & Y[0..m-1]
22+
return L[m][n]

0 commit comments

Comments
 (0)