ปัญหา
เราต้อง implement คลาส MapSum ที่มีเมธอด insert และ sum สำหรับเมธอด insert จะได้รับคู่ (string, integer) string เป็น key integer เป็น value ถ้า key มีอยู่แล้ว จะ override ด้วยค่าใหม่
สำหรับเมธอด sum จะได้รับ string แทน prefix และต้องคืนผลรวมของ value ทั้งหมดที่ key เริ่มต้นด้วย prefix นั้น
ตัวอย่าง
โค้ดด้านล่างนี้
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