Map Sum Pairs
Description
Implement a MapSum class with insert
, and sum
methods.
For the method insert
, you'll be given a pair of (string, integer). The string represents the key and the integer represents the value. If the key already existed, then the original key-value pair will be overridden to the new one.
For the method sum
, you'll be given a string representing the prefix, and you need to return the sum of all the pairs' value whose key starts with the prefix.
Example 1:
Input: insert("apple", 3), Output: Null Input: sum("ap"), Output: 3 Input: insert("app", 2), Output: Null Input: sum("ap"), Output: 5
Solution(javascript)
/*
* @lc app=leetcode id=677 lang=javascript
*
* [677] Map Sum Pairs
*/
// @lc code=start
class TrieNode {
constructor(val) {
this.num = 0
this.val = val
this.children = {}
}
}
/**
* Initialize your data structure here.
*/
const MapSum = function () {
this.root = new TrieNode('')
}
/**
* @param {string} key
* @param {number} val
* @return {void}
*/
MapSum.prototype.insert = function (key, val) {
let node = this.root
for (const c of key) {
if (!node.children[c]) {
node.children[c] = new TrieNode(c)
}
node = node.children[c]
}
node.num = val
}
/**
* @param {string} prefix
* @return {number}
*/
MapSum.prototype.sum = function (prefix) {
let sum = 0
let node = this.root
for (const c of prefix) {
if (!node.children[c]) {
return 0
}
node = node.children[c]
}
const aux = (node) => {
sum += node.num
const { children } = node
Object.keys(children).forEach((key) => {
aux(children[key])
})
}
aux(node)
return sum
}
/**
* Your MapSum object will be instantiated and called as such:
* var obj = new MapSum()
* obj.insert(key,val)
* var param_2 = obj.sum(prefix)
*/
// @lc code=end