LeetCode 677. 键值映射

1、题目描述

LeetCode

2、解题思路

典型的字典树题目,使用其可以快速的匹配前缀操作。每个节点带一个值,如果是单词路径上的节点,权值直接赋值为0即可。

代码

class Trie {
    struct TrieNode {
        int val;
        TrieNode *child[26];
        TrieNode(int x) {
            val = x;
            for (int i = 0; i < 26; i++) {
                child[i] = nullptr;
            }
        }
    };
    TrieNode *root;
public:
    Trie () {
        root = new TrieNode(-1);
    }
    void insert(string& s, int val) {
        auto p = root;
        for (char c : s) {
            if (!p->child[c - 'a']) {
                p->child[c - 'a'] = new TrieNode(0);
            }
            p = p->child[c - 'a'];
        }
        p->val = val;
    }
    int presum(string& s) {
        int sum = 0;
        auto p = root;
        for (char c : s) {
            if (!p->child[c - 'a']) return 0;
            p = p->child[c - 'a'];
        }
        queue<TrieNode*> q;
        q.push(p);
        while (!q.empty()) {
            auto cur = q.front();
            q.pop();
            sum += cur->val;
            for (int i = 0; i < 26; i++) {
                if (cur->child[i]) {
                    q.push(cur->child[i]);
                }
            }
        }
        return sum;
    }
};
class MapSum {    
public:
    /** Initialize your data structure here. */
    Trie *t;
    MapSum() {
        t = new Trie();
    }
    
    void insert(string key, int val) {
        t->insert(key, val);
    }
    
    int sum(string prefix) {
        return t->presum(prefix);
    }
};

/**
 * Your MapSum object will be instantiated and called as such:
 * MapSum* obj = new MapSum();
 * obj->insert(key,val);
 * int param_2 = obj->sum(prefix);
 */

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值