Skip to content

Commit 5bc1455

Browse files
committed
solve: Longest Common Subsequence
1 parent bb38232 commit 5bc1455

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
"""
2+
Constraints:
3+
- 1 <= text1.length, text2.length <= 1000
4+
- text1 and text2 consist of only lowercase English characters.
5+
6+
Time Complexity: O(m*n)
7+
- m์€ text1์˜ ๊ธธ์ด, n์€ text2์˜ ๊ธธ์ด
8+
- @cache๋กœ ์ค‘๋ณต ๊ณ„์‚ฐ์„ ๋ฐฉ์ง€ํ•˜์—ฌ ๊ฐ (i,j) ์กฐํ•ฉ์„ ํ•œ ๋ฒˆ๋งŒ ๊ณ„์‚ฐํ•จ
9+
10+
Space Complexity: O(m*n)
11+
- ์ตœ์•…์˜ ๊ฒฝ์šฐ ํ˜ธ์ถœ ์Šคํƒ์ด ๋‘ ๋ฌธ์ž์—ด ๊ธธ์ด์˜ ๊ณฑ๋งŒํผ ๊นŠ์–ด์ง
12+
13+
ํ’€์ด๋ฐฉ๋ฒ•:
14+
1. DFS์™€ ๋ฉ”๋ชจ์ด์ œ์ด์…˜์„ ์‚ฌ์šฉ
15+
2. ๊ฐ ์œ„์น˜ (i,j)์—์„œ:
16+
- ๋ฌธ์ž๊ฐ€ ๊ฐ™์œผ๋ฉด: ํ˜„์žฌ ๋ฌธ์ž๋ฅผ ํฌํ•จ(+1)ํ•˜๊ณ  ์–‘์ชฝ ๋‹ค์Œ์œผ๋กœ ์ด๋™
17+
- ๋‹ค๋ฅด๋ฉด: ํ•œ์ชฝ๋งŒ ์ด๋™ํ•œ ๊ฒฝ์šฐ ์ค‘ ์ตœ๋Œ“๊ฐ’ ์„ ํƒ
18+
3. base case: ์–ด๋А ํ•œ์ชฝ ๋ฌธ์ž์—ด ๋์— ๋„๋‹ฌํ•˜๋ฉด ์ข…๋ฃŒ
19+
"""
20+
21+
from functools import cache
22+
class Solution:
23+
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
24+
@cache
25+
def dfs(i, j):
26+
if i == len(text1) or j == len(text2):
27+
return 0
28+
29+
if text1[i] == text2[j]:
30+
return 1 + dfs(i + 1, j + 1)
31+
32+
return max(dfs(i + 1, j), dfs(i, j + 1))
33+
34+
return dfs(0, 0)

0 commit comments

Comments
ย (0)