JavaScript 中的映射和对
问题
我们需要使用insert和sum方法实现MapSum类。对于方法插入,我们将得到一对(字符串,整数)。字符串代表键,整数代表值。如果键已经存在,那么原始键值对将被新的键值对覆盖。
对于sum方法,我们将获得一个表示前缀的字符串,我们需要返回键以前缀开头的所有对的值的总和。
示例
以下是代码-
class Node {
constructor(val) {
this.num= 0
this.val= val
this.children= {}
}
}
class MapSum {
constructor(){
this.root= new Node('');
}
}
MapSum.prototype.insert = function (key, val) {
let node = this.root
for (const char of key) {
if (!node.children[char]) {
node.children[char] = new Node(char)
}
node = node.children[char]
}
node.num = val
}
MapSum.prototype.sum = function (prefix) {
let sum = 0
let node = this.root
for (const char of prefix) {
if (!node.children[char]) {
return 0
}
node = node.children[char]
}
const helper = (node) => {
sum += node.num
const { children } = node
Object.keys(children).forEach((key) => {
helper(children[key])
})
}
helper(node)
return sum
}
const m = new MapSum();
console.log(m.insert('apple', 3));
console.log(m.sum('ap'));输出结果undefined 3
热门推荐
10 朋友新年祝福语大全 简短
11 新年祝福语简短大方兔年
12 搬新家礼物祝福语简短
13 同学见面花束祝福语简短
14 五一假期祝福语幽默简短
15 离职欢送敬酒祝福语简短
16 对学弟的祝福语简短
17 考老师辞职祝福语简短
18 祝福语驱散霉运的话简短