Skip to content

Commit cfe4452

Browse files
committed
solve: longest common subsequence
1 parent 6c6a87c commit cfe4452

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
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]

0 commit comments

Comments
ย (0)