-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
49 lines (44 loc) · 1.18 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
class Solution {
class Trie {
class Node {
int score = 0;
Node[] children = new Node[26];
}
private Node root;
public Trie() {
root = new Node();
}
public void insert(String s) {
Node p = root;
for (char c : s.toCharArray()) {
int i = c - 'a';
if (p.children[i] == null) {
p.children[i] = new Node();
}
p = p.children[i];
++p.score;
}
}
public int getScore(String s) {
int result = 0;
Node p = root;
for (char c : s.toCharArray()) {
int i = c - 'a';
p = p.children[i];
result += p.score;
}
return result;
}
}
public int[] sumPrefixScores(String[] words) {
Trie trie = new Trie();
for (String w : words) {
trie.insert(w);
}
int[] result = new int[words.length];
for (int i = 0; i < words.length; ++i) {
result[i] = trie.getScore(words[i]);
}
return result;
}
}