File tree 1 file changed +16
-6
lines changed
1 file changed +16
-6
lines changed Original file line number Diff line number Diff line change 1
1
# 139. Word Break
2
2
class Solution :
3
- def wordBreak (self , s : str , wordDict ) -> bool :
3
+ def wordBreak2 (self , s : str , wordDict ) -> bool :
4
4
if not s or not wordDict :
5
5
return False
6
6
max_len = max (len (w ) for w in wordDict )
7
7
wordSet = set (wordDict )
8
8
9
- queue = collections . deque ()
9
+ queue = set ()
10
10
for i in range (1 , max_len + 1 ):
11
11
if s [:i ] in wordSet :
12
12
if s [i :] == "" :
13
13
return True
14
- queue .append (s [i :])
14
+ queue .add (s [i :])
15
15
16
16
while queue :
17
- cur = queue .popleft ()
17
+ cur = queue .pop ()
18
18
for i in range (1 , min (max_len , len (cur ))+ 1 ):
19
19
if cur [:i ] in wordSet :
20
20
if cur [i :] == "" :
21
21
return True
22
- queue .append (cur [i :])
22
+ queue .add (cur [i :])
23
23
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 ]
You can’t perform that action at this time.
0 commit comments