File tree Expand file tree Collapse file tree 1 file changed +18
-0
lines changed
longest-common-subsequence Expand file tree Collapse file tree 1 file changed +18
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def longestCommonSubsequence (self , text1 , text2 ):
3
+ text1_length , text2_length = len (text1 ), len (text2 )
4
+ # dp[i][j]๋ text1์ ์ฒ์ i ๊ธ์์ text2์ ์ฒ์ j ๊ธ์์ LCS ๊ธธ์ด๋ฅผ ์๋ฏธํฉ๋๋ค.
5
+ dp = [[0 ] * (text2_length + 1 ) for _ in range (text1_length + 1 )]
6
+
7
+ for text1_char in range (1 , text1_length + 1 ):
8
+ for text2_char in range (1 , text2_length + 1 ):
9
+ if text1 [text1_char - 1 ] == text2 [text2_char - 1 ]:
10
+ # ๋ ๋ฌธ์๊ฐ ๊ฐ์ผ๋ฉด ๊ทธ ์ด์ ๊น์ง์ LCS ๊ธธ์ด์ 1์ ๋ํ ๊ฐ์ผ๋ก ํ์ฌ ์์น๋ฅผ ๊ฐฑ์ ํฉ๋๋ค.
11
+ dp [text1_char ][text2_char ] = dp [text1_char - 1 ][text2_char - 1 ] + 1
12
+ else :
13
+ # ๋ ๋ฌธ์๊ฐ ๋ค๋ฅด๋ฉด ์ด์ ๊น์ง์ ์ต๋ LCS ๊ธธ์ด ์ค ๋ ํฐ ๊ฐ์ ํ์ฌ ์์น์ ์ ์ฅํฉ๋๋ค.
14
+ dp [text1_char ][text2_char ] = max (
15
+ dp [text1_char - 1 ][text2_char ], dp [text1_char ][text2_char - 1 ]
16
+ )
17
+
18
+ return dp [text1_length ][text2_length ]
You canโt perform that action at this time.
0 commit comments