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 怎么训练狗狗卧下
4 上海狗狗训练基地
5 训练狗狗排便
6 狗狗基础训练
8 如何训练狗狗装死
9 狗狗站姿训练
10 狗狗训练用品
11 训练狗狗吧
12 狗狗要怎么训练
13 怎么训练狗狗玩球
14 训练狗狗唤回
15 狗狗训练躺下
16 狗狗训练指令
17 狗狗的训练技巧
18 狗狗不好训练