offer2-66


实现一个 MapSum 类,支持两个方法,insertsum

  • MapSum() 初始化 MapSum 对象
  • void insert(String key, int val) 插入 key-val 键值对,字符串表示键 key ,整数表示值 val 。如果键 key 已经存在,那么原来的键值对将被替代成新的键值对。
  • int sum(string prefix) 返回所有以该前缀 prefix 开头的键 key 的值的总和。

示例:

输入:
inputs = ["MapSum", "insert", "sum", "insert", "sum"]
inputs = [[], ["apple", 3], ["ap"], ["app", 2], ["ap"]]
输出:
[null, null, 3, null, 5]

解释:
MapSum mapSum = new MapSum();
mapSum.insert("apple", 3);  
mapSum.sum("ap");           // return 3 (apple = 3)
mapSum.insert("app", 2);    
mapSum.sum("ap");           // return 5 (apple + app = 3 + 2 = 5)

提示:

  • 1 <= key.length, prefix.length <= 50
  • keyprefix 仅由小写英文字母组成
  • 1 <= val <= 1000
  • 最多调用 50insertsum

//leetcode submit region begin(Prohibit modification and deletion)
class MapSum {
    class Trie {
        private Trie[] leaves;
        private int sum;
        Map<String, Integer> valMap;

        public Trie() {
            this.leaves = new Trie[26];
            this.sum = 0;
            this.valMap = new HashMap<>();
        }

        public void addWord(String word, int val) {
            if (word == null) {
                return;
            }
            int value = val;
            if (valMap.containsKey(word)) {
                value -= valMap.get(word);
            }
            valMap.put(word, val);

            Trie trie = this;
            for (int i = 0; i < word.length(); i++) {
                if (trie.leaves[word.charAt(i) - 'a'] == null) {
                    trie.leaves[word.charAt(i) - 'a'] = new Trie();
                }
                trie = trie.leaves[word.charAt(i) - 'a'];
                trie.sum += value;
            }
        }
    }


    private Trie root;

    /** Initialize your data structure here. */
    public MapSum() {
        this.root = new Trie();
    }

    public void insert(String key, int val) {
        this.root.addWord(key, val);
    }

    public int sum(String prefix) {
        if (prefix == null) {
            return 0;
        }

        Trie trie = root;
        for (int i = 0; i < prefix.length(); i++) {
            if (trie.leaves[prefix.charAt(i) - 'a'] == null) {
                return 0;
            }
            trie = trie.leaves[prefix.charAt(i) - 'a'];
        }
        return trie.sum;
    }
}

/**
 * Your MapSum object will be instantiated and called as such:
 * MapSum obj = new MapSum();
 * obj.insert(key,val);
 * int param_2 = obj.sum(prefix);
 */
//leetcode submit region end(Prohibit modification and deletion)

文章作者: 倪春恩
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 倪春恩 !