Skip to content

Commit b2939fc

Browse files
author
Jinbeom
committed
Longest Common Subsequence Solution
1 parent 230f6cb commit b2939fc

File tree

1 file changed

+28
-12
lines changed

1 file changed

+28
-12
lines changed

longest-common-subsequence/kayden.py

Lines changed: 28 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,33 @@
1-
# 시간복잡도: O(N)
2-
# 공간복잡도: O(N)
31
class Solution:
4-
def longestConsecutive(self, nums: List[int]) -> int:
5-
nums = set(nums)
6-
answer = 0
2+
# 시간복잡도: O(A*B)
3+
# 공간복잡도: O(A*B)
4+
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
5+
a = len(text1)
6+
b = len(text2)
77

8-
for num in nums:
9-
if num - 1 not in nums:
10-
length = 1
8+
lcs = [[0]*(b+1) for _ in range(a+1)]
119

12-
while num + length in nums:
13-
length += 1
10+
for i in range(1, a+1):
11+
for j in range(1, b+1):
12+
if text1[i-1] == text2[j-1]:
13+
lcs[i][j] = lcs[i-1][j-1] + 1
14+
lcs[i][j] = max(lcs[i][j], lcs[i-1][j], lcs[i][j-1])
1415

15-
answer = max(answer, length)
16+
return lcs[a][b]
1617

17-
return answer
18+
# 시간복잡도: O(A*B)
19+
# 공간복잡도: O(A)
20+
def longestCommonSubsequence2(self, text1: str, text2: str) -> int:
21+
n = len(text1)
22+
lcs = [0]*n
23+
longest = 0
24+
for ch in text2:
25+
cur = 0
26+
for i in range(n):
27+
if cur < lcs[i]:
28+
cur = lcs[i]
29+
elif ch == text1[i]:
30+
lcs[i] = cur + 1
31+
longest = max(longest, cur+1)
32+
33+
return longest

0 commit comments

Comments
 (0)