forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
51 lines (47 loc) · 1.25 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
class Trie {
Trie[] children = new Trie[26];
boolean isEnd;
void insert(String w) {
Trie node = this;
for (char c : w.toCharArray()) {
c -= 'a';
if (node.children[c] == null) {
node.children[c] = new Trie();
}
node = node.children[c];
}
node.isEnd = true;
}
}
class Solution {
private Trie trie = new Trie();
public List<String> findAllConcatenatedWordsInADict(String[] words) {
Arrays.sort(words, (a, b) -> a.length() - b.length());
List<String> ans = new ArrayList<>();
for (String w : words) {
if (dfs(w)) {
ans.add(w);
} else {
trie.insert(w);
}
}
return ans;
}
private boolean dfs(String w) {
if ("".equals(w)) {
return true;
}
Trie node = trie;
for (int i = 0; i < w.length(); ++i) {
int idx = w.charAt(i) - 'a';
if (node.children[idx] == null) {
return false;
}
node = node.children[idx];
if (node.isEnd && dfs(w.substring(i + 1))) {
return true;
}
}
return false;
}
}