Skip to content

Commit cb252a1

Browse files
committed
solve(w08): 1143. Longest Common Subsequence
1 parent ca66ab0 commit cb252a1

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# https://leetcode.com/problems/longest-common-subsequence/
2+
3+
class Solution:
4+
def longestCommonSubsequence_2d(self, text1: str, text2: str) -> int:
5+
"""
6+
[Complexity]
7+
- TC: O(m * n)
8+
- SC: O(m * n)
9+
10+
[Approach]
11+
dp[i][j] = text1[:i]와 text2[:j]의 longest common subsequence의 길이
12+
= (text1[i - 1] == text2[j - 1] 라면) dp[i - 1][j - 1] + 1 (text1[:i - 1]와 text2[:j - 1]의 longest common subsequence 길이)
13+
(text1[i - 1] != text2[j - 1] 라면) max(dp[i - 1][j], dp[i][j - 1])
14+
"""
15+
m, n = len(text1), len(text2)
16+
17+
dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)]
18+
19+
for i in range(1, m + 1):
20+
for j in range(1, n + 1):
21+
if text1[i - 1] == text2[j - 1]:
22+
dp[i][j] = dp[i - 1][j - 1] + 1
23+
else:
24+
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
25+
26+
return dp[-1][-1]
27+
28+
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
29+
"""
30+
[Complexity]
31+
- TC: O(m * n)
32+
- SC: O(n)
33+
34+
[Approach]
35+
2D DP에서, 현재 row와 이전 row만 필요로 하기 때문에 1D DP로 space optimize 할 수 있다.
36+
dp[i]를 curr로, dp[i - 1]를 prev로 유지한다. (이때, curr와 prev는 len이 n + 1이다.)
37+
"""
38+
m, n = len(text1), len(text2)
39+
40+
prev = [0 for _ in range(n + 1)]
41+
curr = [0 for _ in range(n + 1)]
42+
43+
for i in range(1, m + 1):
44+
for j in range(1, n + 1):
45+
if text1[i - 1] == text2[j - 1]:
46+
curr[j] = prev[j - 1] + 1
47+
else:
48+
curr[j] = max(prev[j], curr[j - 1])
49+
50+
# 다음 row로 넘어가기 위해 바꿔치기
51+
curr, prev = prev, curr
52+
53+
return prev[-1]

0 commit comments

Comments
 (0)