Skip to content

Commit 2093f87

Browse files
committed
feat: word-break 풀이
1 parent f6a68c7 commit 2093f87

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

β€Žword-break/unpo88.pyβ€Ž

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
class Solution:
2+
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
3+
word_set = set(wordDict)
4+
dp = [False] * (len(s) + 1)
5+
dp[0] = True
6+
7+
for i in range(1, len(s) + 1):
8+
for j in range(i):
9+
if dp[j] and s[j:i] in word_set:
10+
dp[i] = True
11+
break
12+
13+
return dp[len(s)]
14+
15+
16+
"""
17+
================================================================================
18+
풀이 κ³Όμ •
19+
================================================================================
20+
21+
[문제 이해]
22+
────────────────────────────────────────────────────────────────────────────────
23+
1. λ¬Έμžμ—΄ s와 사전 wordDictκ°€ 주어짐
24+
2. sλ₯Ό 사전에 μžˆλŠ” λ‹¨μ–΄λ“€λ‘œ λΆ„ν• ν•  수 μžˆλŠ”μ§€ νŒλ‹¨
25+
26+
μ˜ˆμ‹œ 1: s = "leetcode", wordDict = ["leet", "code"]
27+
β†’ True ("leet" + "code")
28+
29+
μ˜ˆμ‹œ 2: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
30+
β†’ False (μ–΄λ–»κ²Œ λ‚˜λˆ λ„ μ•ˆ 됨)
31+
32+
33+
[μ ‘κ·Ό 방법] DP
34+
────────────────────────────────────────────────────────────────────────────────
35+
3. dp[i] = s[0:i]λ₯Ό 사전 λ‹¨μ–΄λ“€λ‘œ λΆ„ν•  κ°€λŠ₯ν•œκ°€?
36+
37+
4. 점화식: dp[i] = dp[j] and s[j:i] in word_set (μ–΄λ–€ j에 λŒ€ν•΄)
38+
- dp[j]κ°€ True이고, s[j:i]κ°€ 사전에 있으면 dp[i] = True
39+
40+
5. μ˜ˆμ‹œ: s = "leetcode"
41+
42+
l e e t c o d e
43+
0 1 2 3 4 5 6 7 8
44+
T ? ? ? T ? ? ? T
45+
β”‚ β”‚ β”‚
46+
λΉˆλ¬Έμžμ—΄ "leet" "code"
47+
48+
dp[4] = dp[0] + "leet" β†’ True
49+
dp[8] = dp[4] + "code" β†’ True
50+
51+
52+
[λ³΅μž‘λ„ 뢄석]
53+
────────────────────────────────────────────────────────────────────────────────
54+
6. μ‹œκ°„λ³΅μž‘λ„: O(nΒ² Γ— m)
55+
- n: λ¬Έμžμ—΄ 길이
56+
- m: 평균 단어 길이 (ν•΄μ‹œ 비ꡐ)
57+
58+
7. κ³΅κ°„λ³΅μž‘λ„: O(n)
59+
- dp λ°°μ—΄ 크기
60+
"""

0 commit comments

Comments
Β (0)