forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution2.java
43 lines (41 loc) · 1.13 KB
/
Solution2.java
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
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
Trie trie = new Trie();
for (String w : wordDict) {
trie.insert(w);
}
int n = s.length();
boolean[] f = new boolean[n + 1];
f[n] = true;
for (int i = n - 1; i >= 0; --i) {
Trie node = trie;
for (int j = i; j < n; ++j) {
int k = s.charAt(j) - 'a';
if (node.children[k] == null) {
break;
}
node = node.children[k];
if (node.isEnd && f[j + 1]) {
f[i] = true;
break;
}
}
}
return f[0];
}
}
class Trie {
Trie[] children = new Trie[26];
boolean isEnd = false;
public void insert(String w) {
Trie node = this;
for (int i = 0; i < w.length(); ++i) {
int j = w.charAt(i) - 'a';
if (node.children[j] == null) {
node.children[j] = new Trie();
}
node = node.children[j];
}
node.isEnd = true;
}
}