JavaScript 中的 Map Sum 对
javascriptweb developmentfront end technology
问题
我们需要实现一个具有 insert 和 sum 方法的 MapSum 类。对于方法 insert,我们将获得一对 (string, integer)。字符串表示键,整数表示值。如果键已经存在,则原始键值对将被新键值对覆盖。
对于方法 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