用 JavaScript 對映求和對
問題
我們需要實現一個 MapSum 類,該類具有 insert 和 sum 方法。對於 insert 方法,我們將得到一對 (字串、整數)。字串表示鍵,整數表示值。如果鍵已存在,則將原來的鍵值對覆蓋為新的鍵值對。
對於 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP