java: add «2416. Sum of Prefix Scores of Strings»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
60cb9ae2e3
commit
f70fcffd6c
1 changed files with 48 additions and 0 deletions
48
java/sum-of-prefix-scores-of-strings.java
Normal file
48
java/sum-of-prefix-scores-of-strings.java
Normal 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;
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue