Skip to content

Commit 861567e

Browse files
committed
add solution: longest-common-subsequence
1 parent 7f8e859 commit 861567e

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

longest-common-subsequence/dusunax.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
'''
2+
# 1143. Longest Common Subsequence
3+
4+
use DP table.
5+
6+
> key: tuple(current index in text1, current index in text2)
7+
> value: LCS of text1[i:] and text2[j:]
8+
'''
9+
class Solution:
10+
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
11+
dp = {}
12+
13+
def helper(i, j):
14+
if i == len(text1) or j == len(text2):
15+
return 0
16+
17+
if (i, j) in dp:
18+
return dp[(i, j)]
19+
20+
if text1[i] == text2[j]:
21+
dp[(i, j)] = 1 + helper(i + 1, j + 1)
22+
else:
23+
dp[(i, j)] = max(helper(i + 1, j), helper(i, j + 1))
24+
25+
return dp[(i, j)]
26+
27+
return helper(0, 0)

0 commit comments

Comments
 (0)