鱼C论坛

 找回密码
 立即注册
查看: 1955|回复: 0

[技术交流] C++刷leetcode(677. 键值映射)【字典树】

[复制链接]
发表于 2020-6-8 10:50:17 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
题目描述:
  1. 实现一个 MapSum 类里的两个方法,insert 和 sum。

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

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

  4. 示例 1:

  5. 输入: insert("apple", 3), 输出: Null
  6. 输入: sum("ap"), 输出: 3
  7. 输入: insert("app", 2), 输出: Null
  8. 输入: sum("ap"), 输出: 5

  9. 来源:力扣(LeetCode)
  10. 链接:https://leetcode-cn.com/problems/map-sum-pairs
  11. 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
复制代码


  1. class MapSum {
  2. private:
  3.     bool isEnd;
  4.     MapSum* next[26];
  5.     vector<int> value;
  6.     set<string> store;
  7. public:
  8.     /** Initialize your data structure here. */
  9.     MapSum() {
  10.         isEnd = false;
  11.         memset(next, 0, sizeof(next));
  12.         value = {};
  13.     }
  14.    
  15.     void insert(string key, int val) {
  16.         MapSum* node = this;
  17.         auto cha = store.insert(key);
  18.         bool flag = cha.second;
  19.         for(auto cha : key){
  20.             if(node -> next[cha - 'a'] == NULL){
  21.                 node -> next[cha - 'a'] = new MapSum();
  22.             }
  23.             node = node -> next[cha - 'a'];
  24.             if(flag == false)node -> value.pop_back();
  25.             node ->value.push_back(val);
  26.         }
  27.         node -> isEnd = true;
  28.     }
  29.    
  30.     int sum(string prefix) {
  31.         MapSum*node = this;
  32.         int res = 0;
  33.         for(auto cha : prefix){
  34.             if(node -> next[cha - 'a'] == NULL) return res;
  35.             node = node -> next[cha - 'a'];
  36.         }
  37.         int len = node -> value.size();
  38.         for(int i = 0; i < len; i++){
  39.             res += node -> value[i];
  40.         }
  41.         return res;
  42.     }
  43. };

  44. /**
  45. * Your MapSum object will be instantiated and called as such:
  46. * MapSum* obj = new MapSum();
  47. * obj->insert(key,val);
  48. * int param_2 = obj->sum(prefix);
  49. */
复制代码

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-7-4 09:41

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表