반응형
1. 문제
- 요구사항에 맞는 MapSum class를 구현하라.
2. 해결
class TrieNode {
children: Map<string,TrieNode>;
sum: Map<string,number>;
constructor() {
this.children = new Map();
this.sum = new Map();
}
}
class MapSum {
root: TrieNode;
constructor() {
this.root = new TrieNode();
}
insert(key: string, val: number): void {
let node = this.root;
for(const char of key) {
if(!node.children.has(char)) {
node.children.set(char, new TrieNode());
}
node = node.children.get(char);
node.sum.set(key, val);
}
}
sum(prefix: string): number {
let node = this.root;
for(const char of prefix) {
if(!node.children.has(char)) {
return 0;
}
node = node.children.get(char);
}
return [...node.sum.values()].reduce((acc, a) => acc+=a, 0);
}
}
/**
* Your MapSum object will be instantiated and called as such:
* var obj = new MapSum()
* obj.insert(key,val)
* var param_2 = obj.sum(prefix)
*/
- 동일한 키로 입력된 value는 덮어 씌워야 하기 때문에 기존에 number로 해놨다가, map으로 변경하여 해결.