Skip to content

Commit 60d36ce

Browse files
Nursultan AmirNursultan Amir
Nursultan Amir
authored and
Nursultan Amir
committed
139. Word Break
1 parent 48dcc12 commit 60d36ce

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

leetcode/380-139. Word Break.py

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# 139. Word Break
2+
class Solution:
3+
def wordBreak(self, s: str, wordDict) -> bool:
4+
if not s or not wordDict:
5+
return False
6+
max_len = max(len(w) for w in wordDict)
7+
wordSet = set(wordDict)
8+
9+
queue = collections.deque()
10+
for i in range(1, max_len+1):
11+
if s[:i] in wordSet:
12+
if s[i:] == "":
13+
return True
14+
queue.append(s[i:])
15+
16+
while queue:
17+
cur = queue.popleft()
18+
for i in range(1, min(max_len, len(cur))+1):
19+
if cur[:i] in wordSet:
20+
if cur[i:] == "":
21+
return True
22+
queue.append(cur[i:])
23+
24+
return False

0 commit comments

Comments
 (0)