File tree Expand file tree Collapse file tree
longest-common-subsequence Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ # 7๊ธฐ ํ์ด
2+ # ์๊ฐ ๋ณต์ก๋: O(n * m)
3+ # - text1์ ๊ธธ์ด n๊ณผ text2์ ๊ธธ์ด m๋งํผ ์ํํ๋ฉฐ ๊ณ์ฐํจ
4+ # ๊ณต๊ฐ ๋ณต์ก๋: O(n * m)
5+ # - text1์ ๊ธธ์ด n๊ณผ text2์ ๊ธธ์ด m๋งํผ์ 2์ฐจ ๋ฐฐ์ด์ ๋ง๋ค์ด DP ๊ณ์ฐ์ ํ๊ธฐ ๋๋ฌธ
6+ class Solution :
7+ def longestCommonSubsequence (self , text1 : str , text2 : str ) -> int :
8+ dp = [
9+ [0 for _ in range (len (text2 ) + 1 )]
10+ for _ in range (len (text1 ) + 1 )
11+ ]
12+
13+ for i in range (1 , len (text1 ) + 1 ):
14+ for j in range (1 , len (text2 ) + 1 ):
15+ if text1 [i - 1 ] == text2 [j - 1 ]:
16+ # text1์ i๋ฒ์งธ ๋ฌธ์์ text2์ j๋ฒ์งธ ๋ฌธ์๊ฐ ๊ฐ๋ค๋ฉด
17+ # ์ด ๋ฌธ์๋ ๊ณตํต subsequence์ ํฌํจ๋ ์ ์์ผ๋ฏ๋ก
18+ # ๋ ๋ฌธ์๋ฅผ ์ ์ธํ ๋๋จธ์ง(dp[i-1][j-1])์ 1์ ๋ํ ๊ฐ์ด ํ์ฌ์ LCS ๊ธธ์ด๊ฐ ๋๋ค
19+ dp [i ][j ] = dp [i - 1 ][j - 1 ] + 1
20+ else :
21+ # ๊ฐ์ง ์๋ค๋ฉด ๋ ์ค ํ๋๋ฅผ ์ ์ธํ์ ๋์ LCS ์ค ๋ ํฐ ๊ฐ์ ๊ฐ์ ธ์จ๋ค
22+ # dp[i][j-1]: text2์ j๋ฒ์งธ ๋ฌธ์๋ฅผ ์ ์ธํ ๊ฒฝ์ฐ
23+ # dp[i-1][j]: text1์ i๋ฒ์งธ ๋ฌธ์๋ฅผ ์ ์ธํ ๊ฒฝ์ฐ
24+ dp [i ][j ] = max (dp [i ][j - 1 ], dp [i - 1 ][j ])
25+
26+ return dp [- 1 ][- 1 ]
You canโt perform that action at this time.
0 commit comments