java: add «2416. Sum of Prefix Scores of Strings»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-09-25 23:18:30 +02:00
parent 60cb9ae2e3
commit f70fcffd6c
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,48 @@
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;
}
}