LeetCode 677. 键值映射

一个简单的Tire树模板题,存个档

 1 class MapSum {
 2 
 3 struct TrieNode {
 4     TrieNode* next[26];
 5     int val;
 6     TrieNode() {
 7         for(int i = 0; i < 26; i++) 
 8             this->next[i] = NULL;
 9         this->val = 0;
10     }
11 };
12 
13 public:
14     MapSum() {
15         root = new TrieNode();
16     }
17     
18     void insert(string key, int val) {
19         int delta = val;
20         if(cnt.count(key))
21             delta -= cnt[key];
22         cnt[key] = val;
23         TrieNode* node = root;
24         for(auto c : key) {
25             if(node->next[c - 'a'] == NULL)
26                 node->next[c - 'a'] = new TrieNode();
27             node = node->next[c - 'a'];
28             node->val += delta;
29         }
30     }
31     
32     int sum(string prefix) {
33         TrieNode* node = root;
34         for(auto c : prefix) {
35             if(node->next[c - 'a'] == NULL)
36                 return 0;
37             node = node->next[c-'a'];
38         }
39         return node->val;
40     }
41 private:
42     unordered_map<string, int> cnt;
43     TrieNode* root;
44 };

 

上一篇:jquery实现全选、不选、反选的两种方法


下一篇:(完美)华为畅玩5 CUN-AL00的Usb调试模式在哪里开启的步骤