Skip to content

Commit 913de8d

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

File tree

1 file changed

+16
-6
lines changed

1 file changed

+16
-6
lines changed

leetcode/380-139. Word Break.py

+16-6
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,34 @@
11
# 139. Word Break
22
class Solution:
3-
def wordBreak(self, s: str, wordDict) -> bool:
3+
def wordBreak2(self, s: str, wordDict) -> bool:
44
if not s or not wordDict:
55
return False
66
max_len = max(len(w) for w in wordDict)
77
wordSet = set(wordDict)
88

9-
queue = collections.deque()
9+
queue = set()
1010
for i in range(1, max_len+1):
1111
if s[:i] in wordSet:
1212
if s[i:] == "":
1313
return True
14-
queue.append(s[i:])
14+
queue.add(s[i:])
1515

1616
while queue:
17-
cur = queue.popleft()
17+
cur = queue.pop()
1818
for i in range(1, min(max_len, len(cur))+1):
1919
if cur[:i] in wordSet:
2020
if cur[i:] == "":
2121
return True
22-
queue.append(cur[i:])
22+
queue.add(cur[i:])
2323

24-
return False
24+
return False
25+
26+
def wordBreak(self, s: str, wordDict) -> bool:
27+
n = len(s)
28+
dp = [True] + [False] * n
29+
30+
for i in range(n):
31+
for w in wordDict:
32+
dp[i+1] = dp[i+1] or (w == s[i-len(w)+1:i+1] and dp[i-len(w)+1])
33+
34+
return dp[-1]

0 commit comments

Comments
 (0)