当前位置:网站首页>LeetCode - 677 键值映射(设计)*
LeetCode - 677 键值映射(设计)*
2022-07-25 15:32:00 【三岁就很萌@D】


前缀树+哈希表


class MapSum {
class TrieNode{
int val = 0;
TrieNode[] child = new TrieNode[26];
}
private TrieNode root;
private Map<String,Integer> map;
public MapSum() {
root = new TrieNode();
map = new HashMap<>();
}
public void insert(String key, int val) {
int delta = val - map.getOrDefault(key,0);
map.put(key,val);
TrieNode node = root;
for(char c : key.toCharArray()){
if(node.child[c - 'a'] == null)
node.child[c - 'a'] = new TrieNode();
node = node.child[c - 'a'];
node.val += delta;
}
}
public int sum(String prefix) {
TrieNode node = root;
int sumPrefix = 0;
for(char c : prefix.toCharArray()){
if(node.child[c - 'a'] == null)
return 0;
node = node.child[c - 'a'];
}
return node.val;
}
}
/** * Your MapSum object will be instantiated and called as such: * MapSum obj = new MapSum(); * obj.insert(key,val); * int param_2 = obj.sum(prefix); */
边栏推荐
猜你喜欢
随机推荐
Gary Marcus: 学习语言比你想象的更难
Submarine cable detector tss350 (I)
Games101 review: 3D transformation
BPSK调制系统MATLAB仿真实现(1)
ICPC2021昆明M-暴力+主席树
Box avoiding mouse
2016CCPC网络选拔赛C-换根dp好题
C#精挑整理知识要点10 泛型(建议收藏)
Pat grade a 1152 Google recruitment (20 points)
伤透脑筋的CPU 上下文切换
图论及概念
Get the ask code corresponding to the key pressed by the keyboard
UITextField的inputView和inputAccessoryView注意点
PAT甲级题目目录
mouseover和mouseenter的区别
Pytorch学习笔记--常用函数总结2
2019 Shaanxi Provincial race K-variant Dijstra
Cf750f1 thinking DP
Xcode added mobileprovision certificate file error: Xcode encoded an error
ML - 自然语言处理 - 关键技术









