Java HashMap and indexof function to check prefix


  • 0
    W

    class MapSum {

    /** Initialize your data structure here. */
    HashMap<String, Integer> map;
    public MapSum() {
        map = new HashMap<>();
    }
    
    public void insert(String key, int val) {
        map.put(key, val);
    }
    
    public int sum(String prefix) {
        int sum = 0;
        for (Map.Entry<String, Integer> entry : map.entrySet()){
            String s = entry.getKey();
            int index = entry.getValue();
            if(s.indexOf(prefix) == 0){
                sum += index;
            }
        }
        return sum;
    }
    

    }


Log in to reply
 

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