forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution2.py
34 lines (31 loc) · 970 Bytes
/
Solution2.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
class Trie:
def __init__(self):
self.children: List[Trie | None] = [None] * 26
self.isEnd = False
def insert(self, w: str):
node = self
for c in w:
idx = ord(c) - ord('a')
if not node.children[idx]:
node.children[idx] = Trie()
node = node.children[idx]
node.isEnd = True
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
trie = Trie()
for w in wordDict:
trie.insert(w)
n = len(s)
f = [False] * (n + 1)
f[n] = True
for i in range(n - 1, -1, -1):
node = trie
for j in range(i, n):
idx = ord(s[j]) - ord('a')
if not node.children[idx]:
break
node = node.children[idx]
if node.isEnd and f[j + 1]:
f[i] = True
break
return f[0]