49 lines
979 B
Java
49 lines
979 B
Java
|
class Solution {
|
||
|
private class TrieNode {
|
||
|
public TrieNode[] next = new TrieNode[26];
|
||
|
public int hits = 0;
|
||
|
}
|
||
|
|
||
|
private void insert(TrieNode root, String word) {
|
||
|
var node = root;
|
||
|
for (var c : word.toCharArray()) {
|
||
|
var idx = c - 'a';
|
||
|
if (node.next[idx] == null) {
|
||
|
node.next[idx] = new TrieNode();
|
||
|
}
|
||
|
|
||
|
++node.next[idx].hits;
|
||
|
|
||
|
node = node.next[idx];
|
||
|
}
|
||
|
}
|
||
|
|
||
|
private int computeScore(TrieNode root, String word) {
|
||
|
var score = 0;
|
||
|
|
||
|
var node = root;
|
||
|
for (var c : word.toCharArray()) {
|
||
|
var idx = c - 'a';
|
||
|
score += node.next[idx].hits;
|
||
|
|
||
|
node = node.next[idx];
|
||
|
}
|
||
|
|
||
|
return score;
|
||
|
}
|
||
|
|
||
|
public int[] sumPrefixScores(String[] words) {
|
||
|
var root = new TrieNode();
|
||
|
for (var word : words) {
|
||
|
insert(root, word);
|
||
|
}
|
||
|
|
||
|
var scores = new int[words.length];
|
||
|
for (int i = 0; i < words.length; ++i) {
|
||
|
scores[i] = computeScore(root, words[i]);
|
||
|
}
|
||
|
|
||
|
return scores;
|
||
|
}
|
||
|
}
|