zoukankan      html  css  js  c++  java
  • Java实现 LeetCode 677 键值映射(字典树)

    677. 键值映射

    实现一个 MapSum 类里的两个方法,insert 和 sum。

    对于方法 insert,你将得到一对(字符串,整数)的键值对。字符串表示键,整数表示值。如果键已经存在,那么原来的键值对将被替代成新的键值对。

    对于方法 sum,你将得到一个表示前缀的字符串,你需要返回所有以该前缀开头的键的值的总和。

    示例 1:

    输入: insert("apple", 3), 输出: Null
    输入: sum("ap"), 输出: 3
    输入: insert("app", 2), 输出: Null
    输入: sum("ap"), 输出: 5
    
    class MapSum {
      class TrieNode{
            TrieNode[] children;
            int count;
            public TrieNode(){
                this.children = new TrieNode[26];
                count=0;
            }
        } 
        TrieNode root;
        public MapSum() {
            root = new TrieNode();
        }
        
        public void insert(String key, int val) {
            TrieNode cur = root;
            for(char c:key.toCharArray()){
                if(cur.children[c-'a']==null){
                    cur.children[c-'a'] = new TrieNode();
                } 
                cur = cur.children[c-'a'];
            }
            cur.count=val;
        }
        
        public int sum(String prefix) {
            TrieNode cur = root;
            int res=0;
            for(char c:prefix.toCharArray()){
                if(cur.children[c-'a']==null)
                    return 0;
                cur = cur.children[c-'a'];
            }
            res=getSum(cur);
            return res;
        }
        public int getSum(TrieNode root){
            int res=root.count;
            for(int i=0;i<26;i++){
                if(root.children[i]!=null){
                    res+=getSum(root.children[i]);
                }
            }
            return res;
        }
    }
    
    /**
     * Your MapSum object will be instantiated and called as such:
     * MapSum obj = new MapSum();
     * obj.insert(key,val);
     * int param_2 = obj.sum(prefix);
     */
    
  • 相关阅读:
    取文本中数字
    成绩统计excel
    excel日期转化为周次
    ConcurrentHashMap之实现细节(转)
    线程互斥(互斥变量)
    Spring的历史论(数据脱敏)
    Java之递归
    触摸java常量池
    利用ant脚本 自动构建svn增量/全量 系统程序升级包
    JDK1.5/1.6/1.7新特性
  • 原文地址:https://www.cnblogs.com/a1439775520/p/13075184.html
Copyright © 2011-2022 走看看