用 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

更新於:2021 年 4 月 24 日

269 次瀏覽

開啟你的 職業

完成課程即可獲得認證

開始吧
廣告
© . All rights reserved.