Skip to content

Commit dafa5ee

Browse files
committed
add solution for word break problem
1 parent 4230e0b commit dafa5ee

1 file changed

Lines changed: 35 additions & 0 deletions

File tree

word-break/gcount85.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
"""
2+
# Intuition
3+
wordDict를 word들의 길이로 분류하고,
4+
s의 각 위치까지의 문자열을 완성할 수 있는지 dp 배열로 확인합니다.
5+
6+
# Complexity
7+
wordDict의 길이를 N, s의 길이를 K
8+
- Time complexity: O(N+K)
9+
- Space complexity: O(N+K)
10+
"""
11+
12+
from collections import defaultdict
13+
14+
15+
class Solution:
16+
def wordBreak(self, s: str, wordDict: list[str]) -> bool:
17+
n = len(s)
18+
dp = [False] * (n + 1)
19+
word_dict = defaultdict(set)
20+
for word in wordDict:
21+
word_dict[len(word)].add(word)
22+
23+
dp[0] = True
24+
for i in range(1, n + 1):
25+
for (
26+
k,
27+
v,
28+
) in word_dict.items():
29+
if i + k - 1 > n:
30+
continue
31+
if dp[i - 1] == False:
32+
continue
33+
if s[i - 1 : i + k - 1] in v:
34+
dp[i + k - 1] = True
35+
return dp[n]

0 commit comments

Comments
 (0)