forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution2.cpp
46 lines (44 loc) · 1.07 KB
/
Solution2.cpp
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
class Trie {
public:
vector<Trie*> children;
bool isEnd;
Trie()
: children(26)
, isEnd(false) {}
void insert(string word) {
Trie* node = this;
for (char c : word) {
c -= 'a';
if (!node->children[c]) node->children[c] = new Trie();
node = node->children[c];
}
node->isEnd = true;
}
};
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
Trie trie;
for (auto& w : wordDict) {
trie.insert(w);
}
int n = s.size();
vector<bool> f(n + 1);
f[n] = true;
for (int i = n - 1; ~i; --i) {
Trie* node = ≜
for (int j = i; j < n; ++j) {
int k = s[j] - 'a';
if (!node->children[k]) {
break;
}
node = node->children[k];
if (node->isEnd && f[j + 1]) {
f[i] = true;
break;
}
}
}
return f[0];
}
};