simple java solution


  • 0
    D

    class MapSum {

    /** Initialize your data structure here. */
    Map<String, Integer> h;
    public MapSum() {
        h = new HashMap<>();
    } 
    public void insert(String key, int val) {
        h.put(key,Integer.valueOf(val)); 
    }
    public int sum(String prefix) {
        int s=0;
            for(Map.Entry m:h.entrySet()){  
                String key=m.getKey().toString();
                if(prefix.length()<=key.length()){
                    String str=key.substring(0,prefix.length());
                    if (str.equals(prefix)) s=s + (int) m.getValue();
                }
            }
       return s; 
    }
    

    }

    /**

    • Your MapSum object will be instantiated and called as such:
    • MapSum obj = new MapSum();
    • obj.insert(key,val);
    • int param_2 = obj.sum(prefix);
      */

Log in to reply
 

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