Skip to content

Commit 5bed476

Browse files
authored
Merge pull request TheAlgorithms#58 from dhruvsaini/patch-1
Create longest common subsequence.py
2 parents ecd2243 + 8e29c83 commit 5bed476

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
"""
2+
LCS Problem Statement: Given two sequences, find the length of longest subsequence present in both of them.
3+
A subsequence is a sequence that appears in the same relative order, but not necessarily continious.
4+
Example:"abc", "abg" are subsequences of "abcdefgh".
5+
"""
6+
def LCS(s1, s2):
7+
m = len(s1)
8+
n = len(s2)
9+
10+
arr = [[0 for i in range(n+1)]for j in range(m+1)]
11+
12+
for i in range(1,m+1):
13+
for j in range(1,n+1):
14+
if s1[i-1] == s2[j-1]:
15+
arr[i][j] = arr[i-1][j-1]+1
16+
else:
17+
arr[i][j] = max(arr[i-1][j], arr[i][j-1])
18+
return arr[m][n]

0 commit comments

Comments
 (0)