Skip to content

Commit 7eaff61

Browse files
authored
Create longest-common-subsequence.py
1 parent b97e547 commit 7eaff61

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

Python/longest-common-subsequence.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# Time: O(m * n)
2+
# Space: O(min(m, n))
3+
4+
class Solution(object):
5+
def longestCommonSubsequence(self, text1, text2):
6+
"""
7+
:type text1: str
8+
:type text2: str
9+
:rtype: int
10+
"""
11+
if len(text1) < len(text2):
12+
return self.longestCommonSubsequence(text2, text1)
13+
14+
dp = [[0 for _ in xrange(len(text2)+1)] for _ in xrange(2)]
15+
for i in xrange(1, len(text1)+1):
16+
for j in xrange(1, len(text2)+1):
17+
dp[i%2][j] = dp[(i-1)%2][j-1]+1 if text1[i-1] == text2[j-1] \
18+
else max(dp[(i-1)%2][j], dp[i%2][j-1])
19+
return dp[len(text1)%2][len(text2)]

0 commit comments

Comments
 (0)