-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path139. Word Break.py
33 lines (33 loc) · 1.04 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
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
"""
results = dict()
def findPrefix(substring):
res = []
for i in wordDict:
if substring.startswith(i):
res.append(i)
return res
def recurse(substring):
if substring in results:
return False
if substring == '':
return True
prefixs = findPrefix(substring)
if not prefixs:
results[substring] = False
return False
for prefix in prefixs:
if recurse(substring[len(prefix):]):
return True
results[substring] = False
return False
return recurse(s)
s = Solution()
res = s.wordBreak(s = "catsandog", wordDict = ["cats","dog","sand","and","cat"])
print(res)