-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathconcatenated-words.java
64 lines (57 loc) · 1.4 KB
/
concatenated-words.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
58
59
60
61
62
63
64
public class Solution {
public class TrieNode {
TrieNode[] links;
boolean isEnd;
public TrieNode() {
links = new TrieNode[26];
isEnd = false;
}
}
public class Trie {
TrieNode root;
public Trie() {
root = new TrieNode();
}
void insert(String word) {
TrieNode cur = root;
for (char c : word.toCharArray()) {
int index = c - 'a';
if (cur.links[index] == null) {
cur.links[index] = new TrieNode();
}
cur = cur.links[index];
}
cur.isEnd = true;
}
boolean isConcat(String word, int offset, TrieNode cur, int num) {
if (offset == word.length() && num > 1) {
return true;
}
for (int i = offset; i < word.length(); i++) {
int index = word.charAt(i) - 'a';
cur = cur.links[index];
if (cur == null) {
return false;
}
if (cur.isEnd && isConcat(word, i+1, root, num+1)) {
return true;
}
}
return false;
}
}
public List<String> findAllConcatenatedWordsInADict(String[] words) {
List<String> res = new ArrayList<>();
if (words == null || words.length == 1) return res;
Trie trie = new Trie();
for (String word: words) {
trie.insert(word);
}
for (String word: words) {
if (trie.isConcat(word, 0, trie.root, 0)) {
res.add(word);
}
}
return res;
}
}