Simple Javascript solution Using String.prototype.slice()


  • 0
    X
    var MapSum = function() {
      this.map = new Map();
    };
    
    MapSum.prototype.insert = function (key, val) {
      this.map.set(key, val);
    };
    
    MapSum.prototype.sum = function (prefix) {
      let times = 0;
      let map = this.map;
      for (let item of map) { 
        if (item[0].slice(0,prefix.length) == (prefix)) { 
          times += item[1];
        }
      }
      return times;
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.