Skip to content

Commit 6ae183c

Browse files
authored
Create Solution.js
1 parent 63ef10d commit 6ae183c

File tree

1 file changed

+42
-0
lines changed
  • solution/2400-2499/2416.Sum of Prefix Scores of Strings

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
class Trie {
2+
constructor() {
3+
this.children = {};
4+
this.cnt = 0;
5+
}
6+
7+
insert(w) {
8+
let node = this;
9+
for (const c of w) {
10+
if (!node.children[c]) {
11+
node.children[c] = new Trie();
12+
}
13+
node = node.children[c];
14+
node.cnt++;
15+
}
16+
}
17+
18+
search(w) {
19+
let node = this;
20+
let ans = 0;
21+
for (const c of w) {
22+
if (!node.children[c]) {
23+
return ans;
24+
}
25+
node = node.children[c];
26+
ans += node.cnt;
27+
}
28+
return ans;
29+
}
30+
}
31+
32+
/**
33+
* @param {string[]} words
34+
* @return {number[]}
35+
*/
36+
var sumPrefixScores = function(words) {
37+
const trie = new Trie();
38+
for (const w of words) {
39+
trie.insert(w);
40+
}
41+
return words.map(w => trie.search(w));
42+
};

0 commit comments

Comments
 (0)