forked from AishwaryaBarai/Leetcode-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path139. Word Break
53 lines (43 loc) · 1.36 KB
/
139. Word Break
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
50
51
52
53
class Trie(object):
def __init__(self):
self.root = {'*':'*'}
def insert(self, word):
current = self.root
for c in word:
if c not in current:
current[c] = {}
current = current[c]
current['*'] = '*'
def search_word(self,word):
current = self.root
for c in word:
if c not in current:
return False
current = current[c]
if '*' in current:
return True
else:
return False
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
trie = Trie()
for w in wordDict:
trie.insert(w)
dp=[False for i in range(len(s)+1)]
dp[0]=True
for i in range(1,len(s)+1):
for j in range(i):
if dp[j] and trie.search_word(s[j:i]):
dp[i] = True
break
return dp[-1]
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
dp = [False] * (len(s) + 1)
dp[0] = True
for i in range(len(s)):
if dp[i]:
for j in range(i + 1, len(s) + 1):
if s[i:j] in wordDict:
dp[j] = True
return dp[-1]