Date:2019-4-21
题目地址:https://leetcode-cn.com/problems/map-sum-pairs/
实现一个 MapSum 类里的两个方法,insert
和 sum
。
对于方法 insert
,你将得到一对(字符串,整数)的键值对。字符串表示键,整数表示值。如果键已经存在,那么原来的键值对将被替代成新的键值对。
对于方法 sum
,你将得到一个表示前缀的字符串,你需要返回所有以该前缀开头的键的值的总和。
示例 1:
输入:
insert(“apple”, 3), 输出: Null
输入:
sum(“ap”), 输出: 3
输入:
insert(“app”, 2), 输出: Null
输入:
sum(“ap”), 输出: 5
解题:
1. 使用 Map 函数:
/**
* Initialize your data structure here.
*/
const MapSum = function() {
this.dic = new Map()
}
/**
* @param {string} key
* @param {number} val
* @return {void}
*/
MapSum.prototype.insert = function(key, val) {
this.dic.set(key,val)
}
/**
* @param {string} prefix
* @return {number}
*/
MapSum.prototype.sum = function(prefix) {
let result = 0
this.dic.forEach((val,key) => {
if(key.indexOf(prefix) === 0){
result += val
}
})
return result
}
/**
* Your MapSum object will be instantiated and called as such:
* var obj = new MapSum()
* obj.insert(key,val)
* var param_2 = obj.sum(prefix)
*/
2. 前缀Trie:
/**
* Initialize your data structure here.
*/
const TrieN = function(key){
this.key = key
this.val = 0
this.child = new Map()
}
TrieN.prototype.insert = function(key, val) {
if(!key) {
this.val = val
return
}
// 单字母插入
let n = this.child.get(key[0])
if (!n) {
n = new TrieN(key[0])
this.child.set(key[0], n)
}
n.insert(key.substr(1), val)
}
TrieN.prototype.sum = function(prefix) {
if(!prefix) {
return this.calculate()
}
let n = this.child.get(prefix[0])
if (!n) {
return 0
}
return n.sum(prefix.substr(1))
}
TrieN.prototype.calculate = function(){
let ret = this.val
for(let value of this.child.values()){
ret += value.calculate()
}
return ret
}
/*
* MapSum
*/
const MapSum = function() {
this.root = new TrieN("")
}
/**
* @param {string} key
* @param {number} val
* @return {void}
*/
MapSum.prototype.insert = function(key, val) {
if(!key) {
return
}
this.root.insert(key, val)
}
/**
* @param {string} prefix
* @return {number}
*/
MapSum.prototype.sum = function(prefix) {
if(!prefix){
return 0
}
return this.root.sum(prefix)
}
/**
* Your MapSum object will be instantiated and called as such:
* var obj = new MapSum()
* obj.insert(key,val)
* var param_2 = obj.sum(prefix)
*/
为什么要做这道题,它的实际运用场景是什么
js中对于前缀Trie的应用和Map函数的使用