-
Notifications
You must be signed in to change notification settings - Fork 0
/
139-Word_Break.py
49 lines (40 loc) · 1.53 KB
/
139-Word_Break.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
## Recursion with memoization
# Time: O(n^3)
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
@lru_cache
def recur( s, word_dict, start ):
if start == len(s):
return True
for end in range( start+1, len(s)+1 ):
if s[start:end] in word_dict and recur( s, word_dict, end ):
return True
return False
return recur( s, frozenset(wordDict), 0 )
class SolutionII:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
memo = [-1]*len(s)
def recur( s, word_dict, start ):
if start == len(s):
return True
if memo[start] != -1:
return memo[start]
for end in range( start+1, len(s)+1 ):
if s[start:end] in word_dict and recur( s, word_dict, end ):
memo[start] = True
return True
memo[start] = False
return False
return recur( s, set(wordDict), 0 )
## Brute Force
# Time: O(2^n)
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
def recur( s, word_dict, start ):
if start == len(s):
return True
for end in range( start+1, len(s)+1 ):
if s[start:end] in word_dict and recur( s, word_dict, end ):
return True
return False
return recur( s, set(wordDict), 0 )