[LeetCode javaScript] 677. 鍵值對映
阿新 • • 發佈:2019-01-11
實現一個 MapSum 類裡的兩個方法,insert 和 sum。
對於方法 insert,你將得到一對(字串,整數)的鍵值對。字串表示鍵,整數表示值。如果鍵已經存在,那麼原來的鍵值對將被替代成新的鍵值對。
對於方法 sum,你將得到一個表示字首的字串,你需要返回所有以該字首開頭的鍵的值的總和。
示例 1:
輸入: insert(“apple”, 3), 輸出: Null
輸入: sum(“ap”), 輸出: 3
輸入: insert(“app”, 2), 輸出: Null
輸入: sum(“ap”), 輸出: 5
/** * Initialize your data structure here. */ var MapSum = function() { this.map={}; }; /** * @param {string} key * @param {number} val * @return {void} */ MapSum.prototype.insert = function(key, val) { this.map[key]=val; }; /** * @param {string} prefix * @return {number} */ MapSum.prototype.sum = function(prefix) { let count=0; for (let t in this.map){ if(t.indexOf(prefix)==0){ count+=this.map[i]; } } return count; }; /** * Your MapSum object will be instantiated and called as such: * var obj = Object.create(MapSum).createNew() * obj.insert(key,val) * var param_2 = obj.sum(prefix) */