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
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下