Skip to content

Commit 5c511e9

Browse files
committed
Added Longest Common Subsequence
1 parent 7bb8661 commit 5c511e9

File tree

4 files changed

+50
-0
lines changed

4 files changed

+50
-0
lines changed
20.6 KB
Loading
23.3 KB
Loading
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
2+
# Longest Common Subsequence
3+
### Aim
4+
- The aim of the script is to find out the maximum length of the common sequence between two strings.
5+
6+
### Purpose
7+
- The main purpose of this script is to show the implementaion of recursion to solve the Longest Common Subsequence.
8+
9+
### Description
10+
Given two string and determine the length of the string which is common subsequence.
11+
12+
### Workflow
13+
`Input:`
14+
s1 = "ABCDEFG",
15+
s2 = "DEFGHI"
16+
17+
`output:`
18+
Length of the LCS: 4
19+
20+
### Explanation
21+
- Find the number of subsequences with lengths ranging from 1,2,..n-1. In Recursion we first passed the two string and length of the two string as parameters.
22+
- We first find the size of the both string if they are both empty string then we return 0.
23+
- And if we matching the charcter of two string and those two charcters are matched then we add one.
24+
- Otherwise we check, if next charcter is match to the this charcter than we go to that side and decrease the size of the string and add one to our answer.
25+
- At the last we get the length of the longest common subsequence.
26+
27+
### Time and Space Complexity
28+
- Time Complexity: `O(len_of_string1*len_of_string2)`
29+
- Space Complexity:`O(len_of_the_lcs)`
30+
31+
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# LCS: There are two strings in which we have to find the length of the longest common subsequence
2+
# Subarray: Continuous sequence in an array
3+
# Subsequence: Need not to be contiguous, but maintains order
4+
# Subset: Same as subsequence except it has empty set
5+
6+
7+
def lcs(n, m, s1, s2):
8+
if n == 0 or m == 0:
9+
return 0
10+
if s1[n - 1] == s2[m - 1]:
11+
return 1 + lcs(n - 1, m - 1, s1, s2);
12+
else:
13+
return max(lcs(n, m - 1, s1, s2), lcs(n - 1, m, s1, s2))
14+
15+
if __name__ == "__main__":
16+
print("Longest Common Subsequence Problem")
17+
s1 = input("First String: ")
18+
s2 = input("Second String: ")
19+
print("Length of the Longest Common Subsequence: ", lcs(len(s1), len(s2), s1, s2))

0 commit comments

Comments
 (0)