实现一个 MapSum 类,支持两个方法,insert 和 sum:
MapSum() 初始化 MapSum 对象
void insert(String key, int val) 插入 key-val 键值对,字符串表示键 key ,整数表示值 val 。如果键 key 已经存在,那么原来的键值对将被替代成新的键值对。
int sum(string prefix) 返回所有以该前缀 prefix 开头的键 key 的值的总和。
示例:
输入:
["MapSum", "insert", "sum", "insert", "sum"]
[[], ["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
key 和 prefix 仅由小写英文字母组成
1 <= val <= 1000
最多调用 50 次 insert 和 sum
class Node{
public:
Node(){
val=0;
}
int get(char c){
if(next.find(c)==next.end()){
return 0;//不存在
}
return 1;//存在
}
int val;
map<char,Node*>next;
};
class MapSum {
public:
/** Initialize your data structure here. */
MapSum() {
root=new Node;
}
void insert(string key, int val) {
int n=key.length();
Node*cur=root;
for(int i=0;i<n;i++){
char c=key[i];
//不存在则添加
if(cur->get(c)==0){
cur->next[c]=new Node;
}
cur=cur->next[c];
}
cur->val= val;
}
int sum(string prefix) {
int n=prefix.length();
Node*cur=root;
for(int i=0;i<n;i++){
char c=prefix[i];
if(cur->get(c)==0){
return 0;
}
cur=cur->next[c];
}
return sum(cur);
}
private:
int sum(Node *node){
if(node->next.size()==0){
return node->val;
}
int s=node->val;;
for(map<char,Node*>::iterator it=node->next.begin();it!=node->next.end();it++){
s+=sum(it->second);
}
return s;
}
Node *root;
};
/**
* Your MapSum object will be instantiated and called as such:
* MapSum* obj = new MapSum();
* obj->insert(key,val);
* int param_2 = obj->sum(prefix);
*/
class Node{
public:
Node(){
val=0;
for(int i=0;i<26;i++){
next[i]=NULL;
}
}
int val;
Node* next[26];
};
class MapSum {
public:
/** Initialize your data structure here. */
MapSum() {
root=new Node;
}
void insert(string key, int val) {
int n=key.length();
Node*cur=root;
for(int i=0;i<n;i++){
char c=key[i];
if(cur->next[c-'a']==NULL){
cur->next[c-'a']=new Node[26];
}
cur=cur->next[c-'a'];
}
cur->val= val;
}
int sum(string prefix) {
int n=prefix.length();
Node*cur=root;
for(int i=0;i<n;i++){
char c=prefix[i];
if(cur->next[c-'a']==NULL){
return 0;
}
cur=cur->next[c-'a'];
}
return sum(cur);
}
private:
int sum(Node *node){
int s=node->val;;
for(int i=0;i<26;i++){
if(node->next[i])s+=sum(node->next[i]);
}
return s;
}
Node *root;
};
/**
* Your MapSum object will be instantiated and called as such:
* MapSum* obj = new MapSum();
* obj->insert(key,val);
* int param_2 = obj->sum(prefix);
*/