forked from Kyrylo-Ktl/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongest Common Subsequence.py
More file actions
39 lines (30 loc) · 997 Bytes
/
Longest Common Subsequence.py
File metadata and controls
39 lines (30 loc) · 997 Bytes
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
from functools import cache
class Solution:
"""
Time: O(n*m)
Memory: O(n*m)
"""
def longestCommonSubsequence(self, first: str, second: str) -> int:
@cache
def lcs(i: int, j: int) -> int:
if i == 0 or j == 0:
return 0
if first[i - 1] == second[j - 1]:
return 1 + lcs(i - 1, j - 1)
return max(lcs(i - 1, j), lcs(i, j - 1))
return lcs(len(first), len(second))
class Solution:
"""
Time: O(n*m)
Memory: O(n*m)
"""
def longestCommonSubsequence(self, first: str, second: str) -> int:
n, m = len(first), len(second)
dp = [[0] * (m + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for j in range(1, m + 1):
if first[i - 1] == second[j - 1]:
dp[i][j] = 1 + dp[i - 1][j - 1]
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
return dp[-1][-1]