forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
57 lines (52 loc) · 1.48 KB
/
Solution.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class Trie {
Trie[] children = new Trie[26];
boolean isEnd;
void insert(String word) {
Trie node = this;
for (char c : word.toCharArray()) {
c -= 'a';
if (node.children[c] == null) {
node.children[c] = new Trie();
}
node = node.children[c];
}
node.isEnd = true;
}
boolean search(String word) {
Trie node = this;
for (char c : word.toCharArray()) {
c -= 'a';
if (node.children[c] == null) {
return false;
}
node = node.children[c];
}
return node.isEnd;
}
}
class Solution {
private Trie trie = new Trie();
public List<String> wordBreak(String s, List<String> wordDict) {
for (String w : wordDict) {
trie.insert(w);
}
List<List<String>> res = dfs(s);
return res.stream().map(e -> String.join(" ", e)).collect(Collectors.toList());
}
private List<List<String>> dfs(String s) {
List<List<String>> res = new ArrayList<>();
if ("".equals(s)) {
res.add(new ArrayList<>());
return res;
}
for (int i = 1; i <= s.length(); ++i) {
if (trie.search(s.substring(0, i))) {
for (List<String> v : dfs(s.substring(i))) {
v.add(0, s.substring(0, i));
res.add(v);
}
}
}
return res;
}
}