Skip to content

Commit c18a4a1

Browse files
committed
O(n^2) time and O(n) space using Queue.
1 parent 10c1a95 commit c18a4a1

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

139. Word Break/139. Word Break.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
"""
2+
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
3+
4+
Note:
5+
6+
The same word in the dictionary may be reused multiple times in the segmentation.
7+
You may assume the dictionary does not contain duplicate words.
8+
Example 1:
9+
10+
Input: s = "leetcode", wordDict = ["leet", "code"]
11+
Output: true
12+
Explanation: Return true because "leetcode" can be segmented as "leet code".
13+
Example 2:
14+
15+
Input: s = "applepenapple", wordDict = ["apple", "pen"]
16+
Output: true
17+
Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
18+
Note that you are allowed to reuse a dictionary word.
19+
Example 3:
20+
21+
Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
22+
Output: false
23+
"""
24+
class Solution:
25+
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
26+
visited = set()
27+
q = collections.deque([0])
28+
while q:
29+
start = q.popleft()
30+
if start not in visited:
31+
for end in range(start+1,len(s)+1):
32+
if s[start:end] in wordDict:
33+
q.append(end)
34+
if end == len(s):
35+
return True
36+
visited.add(start)
37+
return False

0 commit comments

Comments
 (0)