This repository has been archived by the owner on Jul 30, 2020. It is now read-only.
forked from alqamahjsr/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy path1143_Longest_Common_Subsequence.py
65 lines (55 loc) · 1.89 KB
/
1143_Longest_Common_Subsequence.py
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
# Solution 1
class Solution(object):
def longestCommonSubsequence(self, text1, text2):
"""
:type text1: str
:type text2: str
:rtype: int
"""
if len(text1) < len(text2):
small = text1
big = text2
else:
small = text2
big = text1
subsequences = [[0 for _ in range(len(small) + 1)] for _ in range(len(big) + 1)]
for i in range(len(big)):
currentChar = big[i]
for j in range(len(small)):
otherChar = small[j]
if currentChar == otherChar:
subsequences[i + 1][j + 1] = subsequences[i][j] + 1
else:
subsequences[i + 1][j + 1] = max(subsequences[i][j + 1], subsequences[i + 1][j])
return subsequences[-1][-1]
# Solution 2
class Solution(object):
def longestCommonSubsequence(self, text1, text2):
"""
:type text1: str
:type text2: str
:rtype: int
"""
small, big = sorted((text1, text2), key=len)
oddRow = [0 for _ in range(len(small) + 1)]
evenRow = [0 for _ in range(len(small) + 1)]
for i in range(1, len(big) + 1):
if i % 2 == 1:
currentRow = oddRow
prevRow = evenRow
else:
currentRow = evenRow
prevRow = oddRow
currentChar = big[i - 1]
for j in range(1, len(small) + 1):
otherChar = small[j - 1]
if currentChar == otherChar:
currentRow[j] = prevRow[j - 1] + 1
else:
currentRow[j] = max(currentRow[j - 1], prevRow[j])
return oddRow[-1] if len(big) % 2 == 1 else evenRow[-1]
sol = Solution()
text1 = "abcde"
text2 = "ace"
output = sol.longestCommonSubsequence(text1, text2)
print('Res: ', output)