Date:2019-4-21

题目地址:https://leetcode-cn.com/problems/map-sum-pairs/

实现一个 MapSum 类里的两个方法,insertsum
对于方法 insert,你将得到一对(字符串,整数)的键值对。字符串表示键,整数表示值。如果键已经存在,那么原来的键值对将被替代成新的键值对。
对于方法 sum,你将得到一个表示前缀的字符串,你需要返回所有以该前缀开头的键的值的总和。

示例 1:
输入:

insert(“apple”, 3), 输出: Null

输入:

sum(“ap”), 输出: 3

输入:

insert(“app”, 2), 输出: Null

输入:

sum(“ap”), 输出: 5

解题:

1. 使用 Map 函数:

  1. /**
  2. * Initialize your data structure here.
  3. */
  4. const MapSum = function() {
  5. this.dic = new Map()
  6. }
  7. /**
  8. * @param {string} key
  9. * @param {number} val
  10. * @return {void}
  11. */
  12. MapSum.prototype.insert = function(key, val) {
  13. this.dic.set(key,val)
  14. }
  15. /**
  16. * @param {string} prefix
  17. * @return {number}
  18. */
  19. MapSum.prototype.sum = function(prefix) {
  20. let result = 0
  21. this.dic.forEach((val,key) => {
  22. if(key.indexOf(prefix) === 0){
  23. result += val
  24. }
  25. })
  26. return result
  27. }
  28. /**
  29. * Your MapSum object will be instantiated and called as such:
  30. * var obj = new MapSum()
  31. * obj.insert(key,val)
  32. * var param_2 = obj.sum(prefix)
  33. */

2. 前缀Trie:

  1. /**
  2. * Initialize your data structure here.
  3. */
  4. const TrieN = function(key){
  5. this.key = key
  6. this.val = 0
  7. this.child = new Map()
  8. }
  9. TrieN.prototype.insert = function(key, val) {
  10. if(!key) {
  11. this.val = val
  12. return
  13. }
  14. // 单字母插入
  15. let n = this.child.get(key[0])
  16. if (!n) {
  17. n = new TrieN(key[0])
  18. this.child.set(key[0], n)
  19. }
  20. n.insert(key.substr(1), val)
  21. }
  22. TrieN.prototype.sum = function(prefix) {
  23. if(!prefix) {
  24. return this.calculate()
  25. }
  26. let n = this.child.get(prefix[0])
  27. if (!n) {
  28. return 0
  29. }
  30. return n.sum(prefix.substr(1))
  31. }
  32. TrieN.prototype.calculate = function(){
  33. let ret = this.val
  34. for(let value of this.child.values()){
  35. ret += value.calculate()
  36. }
  37. return ret
  38. }
  39. /*
  40. * MapSum
  41. */
  42. const MapSum = function() {
  43. this.root = new TrieN("")
  44. }
  45. /**
  46. * @param {string} key
  47. * @param {number} val
  48. * @return {void}
  49. */
  50. MapSum.prototype.insert = function(key, val) {
  51. if(!key) {
  52. return
  53. }
  54. this.root.insert(key, val)
  55. }
  56. /**
  57. * @param {string} prefix
  58. * @return {number}
  59. */
  60. MapSum.prototype.sum = function(prefix) {
  61. if(!prefix){
  62. return 0
  63. }
  64. return this.root.sum(prefix)
  65. }
  66. /**
  67. * Your MapSum object will be instantiated and called as such:
  68. * var obj = new MapSum()
  69. * obj.insert(key,val)
  70. * var param_2 = obj.sum(prefix)
  71. */

为什么要做这道题,它的实际运用场景是什么

js中对于前缀Trie的应用和Map函数的使用