-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.ts
59 lines (52 loc) · 1.26 KB
/
Solution.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class Trie {
children: Trie[];
val: number;
constructor() {
this.children = new Array(26);
this.val = 0;
}
insert(w: string, x: number) {
let node: Trie = this;
for (const c of w) {
const i = c.charCodeAt(0) - 97;
if (!node.children[i]) {
node.children[i] = new Trie();
}
node = node.children[i];
node.val += x;
}
}
search(w: string): number {
let node: Trie = this;
for (const c of w) {
const i = c.charCodeAt(0) - 97;
if (!node.children[i]) {
return 0;
}
node = node.children[i];
}
return node.val;
}
}
class MapSum {
d: Map<string, number>;
t: Trie;
constructor() {
this.d = new Map();
this.t = new Trie();
}
insert(key: string, val: number): void {
const x = val - (this.d.get(key) ?? 0);
this.d.set(key, val);
this.t.insert(key, x);
}
sum(prefix: string): number {
return this.t.search(prefix);
}
}
/**
* Your MapSum object will be instantiated and called as such:
* var obj = new MapSum()
* obj.insert(key,val)
* var param_2 = obj.sum(prefix)
*/