문제
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