Skip to content

Commit 9a8287d

Browse files
committed
Added Longest Common Subsequence Algorithm
1 parent 24210ed commit 9a8287d

File tree

1 file changed

+48
-0
lines changed
  • pygorithm/dynamic_programming

1 file changed

+48
-0
lines changed

pygorithm/dynamic_programming/lcs.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
"""
2+
A subsequence is a sequence that can be derived from another
3+
sequence by deleting some or no elements without changing the
4+
order of the remaining elements.
5+
6+
For example, 'abd' is a subsequence of 'abcd' whereas 'adc' is not
7+
8+
Given 2 strings containing lowercase english alphabets, find the length
9+
of the Longest Common Subsequence (L.C.S.).
10+
11+
Example:
12+
Input: 'abcdgh'
13+
'aedfhr'
14+
Output: 3
15+
16+
Explanation: The longest subsequence common to both the string is "adh"
17+
18+
Time Complexity : O(M*N)
19+
Space Complexity : O(M*N), where M and N are the lengths of the 1st and 2nd string
20+
respectively.
21+
22+
"""
23+
24+
25+
def longest_common_subsequence(s1, s2):
26+
"""
27+
:param s1: string
28+
:param s2: string
29+
:return: int
30+
"""
31+
m = len(s1)
32+
n = len(s2)
33+
34+
dp = [[0] * (n + 1) for i in range(m + 1)]
35+
"""
36+
dp[i][j] : contains length of LCS of s1[0..i-1] and s2[0..j-1]
37+
"""
38+
39+
for i in range(m + 1):
40+
for j in range(n + 1):
41+
if i == 0 or j == 0:
42+
dp[i][j] = 0
43+
elif s1[i - 1] == s2[j - 1]:
44+
dp[i][j] = dp[i - 1][j - 1] + 1
45+
else:
46+
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
47+
48+
return dp[m][n]

0 commit comments

Comments
 (0)