-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShortestUniquePrefix.java
More file actions
57 lines (47 loc) · 1.42 KB
/
ShortestUniquePrefix.java
File metadata and controls
57 lines (47 loc) · 1.42 KB
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
package Trie;
public class ShortestUniquePrefix {
static String[] findPrefixes(String[] arr, int n) {
String[] ans = new String[n];
Trie root = new Trie();
for (String s : arr) {
Trie.insert(root, s);
}
for (int i = 0; i < n; i++) {
String prefix = Trie.searchPrefix(root, arr[i]);
ans[i] = prefix;
}
return ans;
}
static class Trie {
Trie[] children;
int count;
Trie() {
children = new Trie[26];
count = 0;
}
static void insert(Trie root, String s) {
Trie temp = root;
for (char ch : s.toCharArray()) {
int index = ch - 'a';
if (temp.children[index] == null) {
temp.children[index] = new Trie();
}
temp.children[index].count++;
temp = temp.children[index];
}
}
static String searchPrefix(Trie root, String s) {
StringBuilder res = new StringBuilder();
Trie temp = root;
for (char ch : s.toCharArray()) {
int index = ch - 'a';
res.append(ch);
if (temp.children[index].count == 1) {
break;
}
temp = temp.children[index];
}
return res.toString();
}
}
}