LintCode-559: Trie Service (System Design题)

  1. Trie Service

Build tries from a list of <word, freq> pairs. Save top 10 for each node.

Example
Example1

Input:
<“abc”, 2>
<“ac”, 4>
<“ab”, 9>
Output:<a[9,4,2]<b[9,2]<c[2]<>>c[4]<>>>
Explanation:
Root
/
a(9,4,2)
/
b(9,2) c(4)
/
c(2)
Example2

Input:
<“a”, 10>
<“c”, 41>
<“b”, 50>
<“abc”, 5>
Output: <a[10,5]<b[5]<c[5]<>>>b[50]<>c[41]<>>

这个Trie的实现好像跟那种经典的每个节点分出26个分叉的Trie不太一样。
insert()的代码很重要。下次再学习。

/**
 * Definition of TrieNode:
 * class TrieNode {
 * public:
 *     TrieNode() {}
 *     map<char, TrieNode*> children;
 *     vector<int> top10;
 * };
 */
class TrieService {
private:
    TrieNode* root;

public:
    TrieService() {
        root = new TrieNode();
    }

    TrieNode* getRoot() {
        // Return root of trie root, and 
        // lintcode will print the tree struct.
        return root;
    }

    //important code    
    void insert(string& word, int frequency) {
        TrieNode *p = root;
        for (int i = 0; i < word.size(); ++i) {
            if (p->children.find(word[i]) == p->children.end()) {
                p->children[word[i]] = new TrieNode();
            }
            p = p->children[word[i]];
            helper(p->top10, frequency);
        }
    }
    
    
    //insert to the right place, top10 is sorted from large to small
    void helper(vector<int>& top10, int freq) {
        top10.push_back(freq);
        int top10Size = top10.size();
        if (top10Size == 1) return;
        
        //start from top10Size - 2 as top10Size - 1 is already freq
        for (int i = top10Size - 2; i >= 0; --i) {
            if (top10[i] < top10[i + 1]) {
                int temp = top10[i];
                top10[i] = top10[i + 1];
                top10[i + 1] = temp;
            } else {
                break;
            }
        }
        
        if (top10Size > 10) top10.pop_back();
    }
    
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值