-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.js
64 lines (55 loc) · 1.33 KB
/
solution.js
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
60
61
62
63
64
/**
* Initialize your data structure here.
*/
var MapSum = function() {
this.root = new TrieNode()
};
var TrieNode = function() {
this.children = {}
this.val = null
}
/**
* @param {string} key
* @param {number} val
* @return {void}
*/
MapSum.prototype.insert = function(key, val) {
let node = this.root
for (let i = 0; i < key.length; i++) {
let char = key[i]
if (node.children[char] === undefined) {
node.children[char] = new TrieNode()
}
node = node.children[char]
}
node.val = val
};
/**
* @param {string} prefix
* @return {number}
*/
MapSum.prototype.sum = function(prefix) {
let sum = 0,
node = this.root
for (let i = 0; i < prefix.length; i++) {
let char = prefix[i]
if (node.children[char] === undefined) {
return 0
}
node = node.children[char]
}
sum += node.val ? node.val : 0
let stack = Object.values(node.children)
while (stack.length > 0) {
node = stack.pop()
stack = stack.concat(Object.values(node.children))
sum += node.val ? node.val : 0
}
return sum
};
/**
* Your MapSum object will be instantiated and called as such:
* var obj = Object.create(MapSum).createNew()
* obj.insert(key,val)
* var param_2 = obj.sum(prefix)
*/