-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongest-common-subsequence.py
More file actions
65 lines (51 loc) · 2.18 KB
/
Copy pathlongest-common-subsequence.py
File metadata and controls
65 lines (51 loc) · 2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
'''
Longest Common Subsequence (LCS)
Last Updated : 23 Aug, 2024
Given two strings, S1 and S2, the task is to find the length of the Longest Common Subsequence. If there is no common subsequence, return 0. A subsequence is a string generated from the original string by deleting 0 or more characters and without changing the relative order of the remaining characters. For example , subsequences of “ABC” are “”, “A”, “B”, “C”, “AB”, “AC”, “BC” and “ABC”. In general a string of length n has 2n subsequences.
LCS problem has great applications like diff utility (find the difference between two files) that we use in our day to day software development.
Examples:
Input: S1 = “ABC”, S2 = “ACD”
Output: 2
Explanation: The longest subsequence which is present in both strings is “AC”.
Input: S1 = “AGGTAB”, S2 = “GXTXAYB”
Output: 4
Explanation: The longest common subsequence is “GTAB”.
Input: S1 = “ABC”, S2 = “CBA”
Output: 1
Explanation: There are three common subsequences of length 1, “A”, “B” and “C” and no common subsequence of length more than 1.
'''
inputs = [
['ABC', 'ACD'],
['AGGTAB', 'GXTXAYB'],
['ABC', 'CBA']
]
def check_small_string(s1, s2):
if len(s1) < len(s2):
return s1, s2
else:
return s2, s1
def check_for_char_match(small, char, j, m):
if j == m:
return [0, 0]
else:
if small[j] == char:
return [1, j]
return check_for_char_match(small, char, j+1, m)
def longest_common_subsequence(small, large, i, n, mx, lf):
if n == i:
return 0
else:
res = check_for_char_match (small, large[i], lf, len(small))
# set last found index to res[1] for next iteration of small word
if res[1] != 0:
lf = res[1]
mx += res[0]
return max(mx, longest_common_subsequence(small, large, i+1, n, mx, lf))
def run_examples():
count = 1
for arr in inputs:
small, large = check_small_string(arr[0], arr[1])
print ('example {} - LIS {}'.format(count, longest_common_subsequence(small, large, 0, len(large), 0, 0)))
count += 1
if __name__ == '__main__':
run_examples()