-
-
Notifications
You must be signed in to change notification settings - Fork 9k
/
Copy pathSolution.java
56 lines (53 loc) · 1.55 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
52
53
54
55
56
class Trie {
Trie[] children = new Trie[26];
int[] v = new int[26];
void insert(String w) {
Trie node = this;
int t = w.charAt(w.length() - 1) - 'a';
for (char c : w.toCharArray()) {
c -= 'a';
if (node.children[c] == null) {
node.children[c] = new Trie();
}
node = node.children[c];
node.v[t]++;
}
}
String search(String w) {
Trie node = this;
StringBuilder res = new StringBuilder();
int t = w.charAt(w.length() - 1) - 'a';
for (int i = 0; i < w.length() - 1; ++i) {
char c = w.charAt(i);
node = node.children[c - 'a'];
res.append(c);
if (node.v[t] == 1) {
break;
}
}
int n = w.length() - res.length() - 1;
if (n > 0) {
res.append(n);
}
res.append(w.charAt(w.length() - 1));
return res.length() < w.length() ? res.toString() : w;
}
}
class Solution {
public List<String> wordsAbbreviation(List<String> words) {
Map<Integer, Trie> trees = new HashMap<>();
for (String w : words) {
if (!trees.containsKey(w.length())) {
trees.put(w.length(), new Trie());
}
}
for (String w : words) {
trees.get(w.length()).insert(w);
}
List<String> ans = new ArrayList<>();
for (String w : words) {
ans.add(trees.get(w.length()).search(w));
}
return ans;
}
}