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 生日广州男生祝福语简短