Skip to content

Commit b98fbd2

Browse files
authored
Create Longest Common Subsequence - Leetcode 1143.py
1 parent 55add41 commit b98fbd2

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
class Solution:
2+
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
3+
# Top Down DP (Memoization)
4+
# Time: O(m*n)
5+
# Space: O(m*n)
6+
7+
m, n = len(text1), len(text2)
8+
9+
@cache
10+
def longest(i, j):
11+
if i == m or j == n:
12+
return 0
13+
elif text1[i] == text2[j]:
14+
return 1 + longest(i+1, j+1)
15+
else:
16+
return max(longest(i, j+1), longest(i+1, j))
17+
18+
return longest(0, 0)
19+
20+
class Solution:
21+
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
22+
# Bottom Up DP (Tabulation)
23+
# Time: O(m*n)
24+
# Space: O(m*n)
25+
26+
m, n = len(text1), len(text2)
27+
dp = [[0] * (n+1) for _ in range(m + 1)]
28+
29+
for i in range(1, m+1):
30+
for j in range(1, n+1):
31+
if text1[i-1] == text2[j-1]:
32+
dp[i][j] = dp[i-1][j-1] + 1
33+
else:
34+
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
35+
36+
return dp[m][n]
37+
38+
39+

0 commit comments

Comments
 (0)