-
Notifications
You must be signed in to change notification settings - Fork 481
/
1408.java
41 lines (37 loc) · 1.06 KB
/
1408.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
class Solution {
public List<String> stringMatching(String[] words) {
Trie root = new Trie();
for (String word : words) {
for (int i = 0; i < word.length(); i++) {
root.insert(word.substring(i));
}
}
List<String> res = new ArrayList();
for (String word : words) {
if (root.get(word)) res.add(word);
}
return res;
}
}
class Trie {
public int val;
public Trie[] next = new Trie[26];
public void insert(String str) {
Trie cur = this;
for (int i = 0; i < str.length(); i++) {
int j = str.charAt(i) - 'a';
if (cur.next[j] == null) cur.next[j] = new Trie();
cur = cur.next[j];
cur.val++;
}
}
public boolean get(String str) {
Trie cur = this;
for (int i = 0; i < str.length(); i++) {
int j = str.charAt(i) - 'a';
if (cur.next[j] == null) return false;
cur = cur.next[j];
}
return cur.val > 1;
}
}