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+ ๋ ๋ฌธ์์ด text1, text2๊ฐ ์ฃผ์ด์ก์ ๋, ์์๋ฅผ ์ ์งํ๋ ๊ณตํต ๋ถ๋ถ ์์ด ์ค ๊ฐ์ฅ ๊ธด ๊ธธ์ด๋ฅผ ๋ฐํํด๋ผ
3+ - ์์ผ๋ฉด 0 ๋ฐํ
4+ - ์์๋ ์ผ์นํด์ผ ํ์ง๋ง, ๋ฌธ์์ด ์ญ์ ๊ฐ๋ฅ
5+ - ์๋ฌธ์๋ก๋ง ์ด๋ฃจ์ด์ ธ ์์.
6+ - 1 <= text1.length, text2.length <= 1000
7+
8+ # LCS DP ํ์ด
9+ - dp[i][j]: ๋ฌธ์์ด text1[:i]์ text2[:j]๊น์ง์ LCS ๊ธธ์ด
10+
11+ 1. text1[i - 1] == text2[j - 1], ๋ ๋ฌธ์์ด์ด ๊ฐ์ ๊ฒฝ์ฐ
12+ LCS ๊ธธ์ด ์ฆ๊ฐ
13+ dp[i][j] = dp[i - 1][j - 1] + 1
14+ 2. ๋ค๋ฅธ ๊ฒฝ์ฐ
15+ text1[0...i] ๋๋ text2[0...j] ์ค ํ๋๋ฅผ ์ค์ธ LCS ์ค ๋ ๊ธด ์ชฝ ์ ํ
16+ dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
17+
18+
19+ TC: O(m * n)
20+ SC: O(m * n)
21+ """
22+
23+ class Solution :
24+ def longestCommonSubsequence (self , text1 : str , text2 : str ) -> int :
25+ m , n = len (text1 ), len (text2 )
26+ dp = [[0 ] * (n + 1 ) for _ in range (m + 1 )] # 0๋ฒ์งธ ์ธ๋ฑ์ค๋ฅผ ๋น์๋ฌ์ ๋ฌธ์์ด์ด ""์ผ ๋๋ฅผ ๊ธฐ๋ณธ๊ฐ์ผ๋ก ์ฒ๋ฆฌ
27+
28+ for i in range (1 , m + 1 ): # text1์ 1 ~ m ์ธ๋ฑ์ค
29+ for j in range (1 , n + 1 ): # text2์ 1 ~ n ์ธ๋ฑ์ค
30+ if text1 [i - 1 ] == text2 [j - 1 ]:
31+ dp [i ][j ] = dp [i - 1 ][j - 1 ] + 1 # ๋ ๋ฌธ์๊ฐ ๊ฐ์ผ๋ฉด, ์ด์ ์ํ + 1
32+ else :
33+ dp [i ][j ] = max (dp [i - 1 ][j ], dp [i ][j - 1 ]) # ๋ค๋ฅด๋ฉด, ํ๋ ์ค์ธ ์ํ ์ค ์ต๋๊ฐ ์ ํ
34+ return dp [m ][n ]
You canโt perform that action at this time.
0 commit comments