File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed
longest-common-subsequence Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change
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 )
You canโt perform that action at this time.
0 commit comments