-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshortestUniquePrefix.java
80 lines (67 loc) · 2.15 KB
/
shortestUniquePrefix.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/*
Find shortest unique prefix to represent each word in the list.
Example:
Input: [zebra, dog, duck, dove]
Output: {z, dog, du, dov}
where we can see that
zebra = z
dog = dog
duck = du
dove = dov
NOTE : Assume that no word is prefix of another. In other words, the representation is always possible.
*/
class Trie {
Trie[] children = new Trie[256];
int frequency;
Trie() {
frequency = 1;
for (int i = 0; i < 256; i++)
children[i] = null;
}
void insert(String key) {
int level;
int length = key.length();
int index;
Trie p = root;
for (level = 0; level < length; level++) {
index = key.charAt(level);
if (p.children[index] == null) {
p.children[index] = new Trie();
} else
p.children[index].frequency = p.children[index].frequency + 1;
p = p.children[index];
}
}
String getSmallestPRefix(String key) {
int level;
int length = key.length();
int index;
Trie p = root;
String str = "";
for (level = 0; level < length; level++) {
index = key.charAt(level);
if (p.children[index].frequency != 1) {
str += key.charAt(level);
p = p.children[index];
} else {
str += key.charAt(level);
break;
}
}
return str;
}
};
Trie root = new Trie();
public ArrayList<String> prefix(ArrayList<String> a) {
if (a == null || a.isEmpty())
return null;
ArrayList<String> result = new ArrayList<String>();
Trie trie = new Trie();
for (int i = 0; i < a.size(); i++) {
trie.insert(a.get(i));
}
for (int i = 0; i < a.size(); i++) {
result.add(trie.getSmallestPRefix(a.get(i)));
}
return result;
}