Skip to content

Commit f5d0cd4

Browse files
committed
https://leetcode.cn/problems/sum-of-prefix-scores-of-strings/
1 parent 96158e0 commit f5d0cd4

File tree

3 files changed

+33
-4
lines changed

3 files changed

+33
-4
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ leetcode 测试
1010

1111
##### 包含的内容如下
1212

13+
https://leetcode.cn/problems/sum-of-prefix-scores-of-strings/
14+
1315
https://leetcode.cn/problems/count-days-spent-together/
1416

1517
https://leetcode.cn/problems/reverse-odd-levels-of-binary-tree/

implement-trie-prefix-tree/PrefixTreeSearchPrefix.ts

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,4 @@
1-
import { TrieNode } from "../implement-trie-ii-prefix-tree/TrieNode.ts";
2-
import { PrefixTree } from "./PrefixTree.ts";
3-
4-
export function PrefixTreeSearchPrefix<T extends PrefixTree | TrieNode>(
1+
export function PrefixTreeSearchPrefix<T extends { children: Map<string, T> }>(
52
root: T,
63
prefix: string,
74
{
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import { TrieNode } from "../implement-trie-ii-prefix-tree/TrieNode.ts";
2+
import { TrieNodeInsert } from "../implement-trie-ii-prefix-tree/TrieNodeInsert.ts";
3+
import { PrefixTreeSearchPrefix } from "../implement-trie-prefix-tree/PrefixTreeSearchPrefix.ts";
4+
function sumPrefixScores(words: string[]): number[] {
5+
const root = new TrieNode();
6+
for (const word of words) {
7+
TrieNodeInsert(root, word);
8+
}
9+
const word2sum = new Map<string, number>();
10+
return words.map((word) => {
11+
const sum = word2sum.get(word) ?? TrieNodeSum(root, word);
12+
word2sum.set(word, sum);
13+
return sum;
14+
});
15+
}
16+
export default sumPrefixScores;
17+
18+
function TrieNodeSum(root: TrieNode, word: string): number {
19+
let sum = 0;
20+
let index = 0;
21+
PrefixTreeSearchPrefix(root, word, {
22+
each(node) {
23+
if (index) {
24+
sum += node.prefixCount;
25+
}
26+
index++;
27+
},
28+
});
29+
return sum;
30+
}

0 commit comments

Comments
 (0)