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);
 */
posted on 2017-09-24 00:31  Beserious  阅读(219)  评论(0编辑  收藏  举报