zoukankan      html  css  js  c++  java
  • leetcode 677. Map Sum Pairs

    Implement a MapSum class with insert, and sum methods.

    For the method insert, you'll be given a pair of (string, integer). The string represents the key and the integer represents the value. If the key already existed, then the original key-value pair will be overridden to the new one.

    For the method sum, you'll be given a string representing the prefix, and you need to return the sum of all the pairs' value whose key starts with the prefix.

    Example 1:
    Input: insert("apple", 3), Output: Null
    Input: sum("ap"), Output: 3
    Input: insert("app", 2), Output: Null
    Input: sum("ap"), Output: 5
    

    题目大意:
    实现一个Mapsum,Maxsum包括两个操作:
    insert:插入字符串和相应的值
    sum("xxx"):查询以xxx为前缀的字符串的值的和
    思路:
    一看就是字典树啊,查询的时候套个dfs就行了

    
    class MapSum {
    public:
        class node {
          public:
            node* next[26];
            int end;
            node() {
                for (int i = 0; i < 26; ++i) {
                    next[i] = nullptr;
                }
                end = 0;
            }
        };
        node* root;
        /** Initialize your data structure here. */
        MapSum() {
            root = new node();
        }
        
        void insert(string key, int val) {
            if (key.size() == 0) return ;
            node* p = root;
            for (int i = 0; i < key.size(); ++i) {
                int x = key[i] - 'a';
                if (p->next[x] == nullptr) {
                    p->next[x] = new node();
                    //p->end += val;
                    p = p->next[x];
                } else {
                    //p->end += val;
                    p = p->next[x];
                }
            }
            p->end = val; 
        }
        
        int sum(string prefix) {
            node* p = root;
            int sum = 0;
            for (int i = 0; i < prefix.size(); ++i) {
                int x = prefix[i] - 'a';
                if (p->next[x] != nullptr) {
                    p = p->next[x];
                } else {
                    return false;
                }
            }
            //sum += p->end;
            dfs(p, sum);
            return sum;
        }
        void dfs(node *p, int& sum) {
            sum += p->end;
            for (int i = 0; i < 26; ++i) {
                if (p->next[i] != nullptr) {
                    dfs(p->next[i], sum);
                }
            }
        }
    };
    
    /**
     * Your MapSum object will be instantiated and called as such:
     * MapSum obj = new MapSum();
     * obj.insert(key,val);
     * int param_2 = obj.sum(prefix);
     */
    
  • 相关阅读:
    Linux常用命令
    C# 报表设计器 (winform 设计端)开发与实现生成网页的HTML报表
    完成复杂表头列表
    流程设计--页面介绍
    流程设计--设计理念
    报表设计--坐标实例-位移坐标
    Spring MVC 工作原理--自我理解
    java ==、equals和hashCode的区别和联系
    java 自动装箱和拆箱
    java maven笔记
  • 原文地址:https://www.cnblogs.com/pk28/p/7583634.html
Copyright © 2011-2022 走看看