1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-10-18 14:52:09 +02:00
LeetCode/java/sum-of-prefix-scores-of-strings.java

49 lines
979 B
Java
Raw Normal View History

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;
}
}