每日打卡

2021-11-14 677键值映射

2021-11-14  本文已影响0人  16孙一凡通工

java hashmap解决insert方法,接着用startsWith方法解决前缀判定,但这不具有普适性,因此参考了前缀树的思路

Go版本

type tribeTree struct{
    children [26]*tribeTree
    val      int
    }

type MapSum struct {
   root *tribeTree
   cnt   map[string]int

}


func Constructor() MapSum {
return MapSum{&tribeTree{},map[string]int{}}
}


func (m *MapSum) Insert(key string, val int)  {
  delta:=val
  if m.cnt[key]>0{
      delta-=m.cnt[key];
  }
  m.cnt[key]=val;
  node:=m.root;
  for _,value:=range key{
      value-='a'
      if  node.children[value]==nil{
          node.children[value]=&tribeTree{}
      }
      node=node.children[value]
      node.val+=delta
  }

}


func (m *MapSum) Sum(prefix string) int {

    node:=m.root;
    for _,value:=range prefix{
        value-='a';
        if node.children[value]==nil{
            return 0
        }
        node=node.children[value]
    }
    return node.val;

}
/**
 * Your MapSum object will be instantiated and called as such:
 * obj := Constructor();
 * obj.Insert(key,val);
 * param_2 := obj.Sum(prefix);
 */

java版本

class MapSum {
     HashMap<String,Integer> hashmap=new HashMap<>();

    public MapSum() {
         HashMap<String,Integer> hashmap=new HashMap<>();
       this.hashmap=hashmap;
    }
    
    public void insert(String key, int val) {
        hashmap.put(key,val);

    }
    
    public int sum(String prefix) {
        int tmp=0;

        for( String key:this.hashmap.keySet()){
          if(key.startsWith(prefix)){
              tmp=tmp+hashmap.get(key);
          } 
        }
        return tmp;

    }
}
上一篇 下一篇

猜你喜欢

热点阅读