Skip to content

Commit c8b2d2a

Browse files
committed
[7th batch] week 8 - longest common subsequence
1 parent 775b2af commit c8b2d2a

1 file changed

Lines changed: 26 additions & 0 deletions

File tree

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

0 commit comments

Comments
ย (0)