鱼C论坛

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

[技术交流] C++刷LeetCode(剑指 Offer II 066. 单词之和)【字典树】【map】

[复制链接]
发表于 2022-2-9 21:42:18 | 显示全部楼层 |阅读模式

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

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

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

  2. MapSum() 初始化 MapSum 对象
  3. void insert(String key, int val) 插入 key-val 键值对,字符串表示键 key ,整数表示值 val 。如果键 key 已经存在,那么原来的键值对将被替代成新的键值对。
  4. int sum(string prefix) 返回所有以该前缀 prefix 开头的键 key 的值的总和。
  5.  

  6. 示例:

  7. 输入:
  8. inputs = ["MapSum", "insert", "sum", "insert", "sum"]
  9. inputs = [[], ["apple", 3], ["ap"], ["app", 2], ["ap"]]
  10. 输出:
  11. [null, null, 3, null, 5]

  12. 解释:
  13. MapSum mapSum = new MapSum();
  14. mapSum.insert("apple", 3);  
  15. mapSum.sum("ap");           // return 3 (apple = 3)
  16. mapSum.insert("app", 2);   
  17. mapSum.sum("ap");           // return 5 (apple + app = 3 + 2 = 5)
  18.  

  19. 提示:

  20. 1 <= key.length, prefix.length <= 50
  21. key 和 prefix 仅由小写英文字母组成
  22. 1 <= val <= 1000
  23. 最多调用 50 次 insert 和 sum
  24. &#160;

  25. 注意:本题与主站 677&#160;题相同:&#160;https://leetcode-cn.com/problems/map-sum-pairs/

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



  1. class MapSum {
  2. private:
  3.     struct Trie{
  4.         set<string>words;
  5.         map<char, Trie*>next;
  6.     };
  7.     Trie* root;
  8.     map<string, int>score;
  9. public:
  10.     /** Initialize your data structure here. */
  11.     MapSum() {
  12.         root = new Trie();
  13.     }
  14.    
  15.     void insert(string key, int val) {
  16.         score[key] = val;
  17.         //构建前缀树
  18.         int len = key.size();
  19.         Trie* node = root;
  20.         for(int i = 0; i < len; i++){
  21.             if((node -> next).count(key[i]) == 0){
  22.                 node -> next[key[i]] = new Trie();
  23.             }
  24.             node = node -> next[key[i]];
  25.             (node -> words).insert(key);
  26.         }
  27.     }
  28.    
  29.     int sum(string prefix) {
  30.         //查找前缀
  31.         int res = 0;
  32.         Trie* node = root;
  33.         for(auto cha : prefix){
  34.             if((node -> next).count(cha) == 0){
  35.                 return 0;
  36.             }
  37.             node = node -> next[cha];
  38.         }
  39.         for(auto it = (node -> words).begin(); it != (node -> words).end(); it++){
  40.             res += score[*it];
  41.         }
  42.         return res;
  43.     }
  44. };

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

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-4-19 13:09

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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