Java8 TreeMap based solution


  • 0
    T
    class MapSum {
        TreeMap<String, Integer> map = null;
    
        /** Initialize your data structure here. */
        public MapSum() {
            map = new TreeMap<>();
        }
        
        public void insert(String key, int val) {
            map.put(key, val);
        }
        
        public int sum(String prefix) {
            // use subMap() of TreeMap to grab all key-value pairs between
            // prefix and prefix + "}" - assume keys only contain letters.
            return map.subMap(prefix, prefix + "{").values().stream().mapToInt(Integer::intValue).sum();
        }
    }

Log in to reply
 

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