Skip to content

Commit 14d8c3b

Browse files
committed
- Longest Common Subsequence #274
1 parent 3043f4e commit 14d8c3b

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class Solution:
2+
"""
3+
- Time Complexity: O(mn), m = len(text1), n = len(text2)
4+
- Space Complexity: O(mn), The size of the dp variable
5+
"""
6+
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
7+
m, n = len(text1), len(text2)
8+
dp = [ [0] * (n + 1) for _ in range(m + 1) ]
9+
10+
for i in range(m):
11+
for j in range(n):
12+
if text1[i] == text2[j]:
13+
# if matched, increase length
14+
dp[i + 1][j + 1] = dp[i][j] + 1
15+
else:
16+
# if unmatched, select a larger length from left and up position
17+
dp[i + 1][j + 1] = max(dp[i + 1][j], dp[i][j + 1])
18+
19+
return dp[m][n]
20+
21+
22+
tc = [
23+
("abcde", "ace", 3),
24+
("abc", "abc", 3),
25+
("abc", "def", 0)
26+
]
27+
28+
sol = Solution()
29+
for i, (s1, s2, e) in enumerate(tc, 1):
30+
r = sol.longestCommonSubsequence(s1, s2)
31+
print(f"TC {i} is Passed!" if r == e else f"TC {i} is Failed! - Expected: {e}, Result: {r}")

0 commit comments

Comments
 (0)