Skip to content

Commit 2bd4318

Browse files
committed
longest-common-subsequence solution (py)
1 parent fe72e2f commit 2bd4318

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
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(m): # text1์˜ 0 ~ m-1 ์ธ๋ฑ์Šค
29+
for j in range(n): # text2์˜ 0 ~ n-1 ์ธ๋ฑ์Šค
30+
if text1[i] == text2[j]:
31+
dp[i + 1][j + 1] = dp[i][j] + 1 # ๋‘ ๋ฌธ์ž๊ฐ€ ๊ฐ™์œผ๋ฉด, ์ด์ „ ์ƒํƒœ + 1
32+
else:
33+
dp[i + 1][j + 1] = max(dp[i][j + 1], dp[i + 1][j]) # ๋‹ค๋ฅด๋ฉด, ํ•˜๋‚˜ ์ค„์ธ ์ƒํƒœ ์ค‘ ์ตœ๋Œ“๊ฐ’ ์„ ํƒ
34+
return dp[m][n]

0 commit comments

Comments
ย (0)