码迷,mamicode.com
首页 > 编程语言 > 详细

字典树(Trie)的基本实现(C++)

时间:2014-09-09 11:03:08      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:blog   io   for   div   sp   log   on   c   amp   

简要说明一下:

主要实现了两个操作,get,set

get用来查找字符串键值对应的value,set则用来向字典树添加key-value对。

这个实现参考自Algorithms 4th Edition, Robert Sedgewick

 

const int inf = -(1 << 30);

struct Node{
    int val;
    Node** next;
    Node(){
        val = -(1 << 30);
        next = new Node*[256];
        for (int i = 0; i < 256; i++)
            next[i] = NULL;
    }
};

class Tries{
private:
    Node* root;

    Node* get(Node* root, string key, int d)
    {
        if (root == NULL)
            return NULL;
        if (d == key.size())
            return root;

        return get(root->next[key[d]], key, d + 1);

    }

    Node* set(Node* root, string key, int val, int d)
    {
        if (root == NULL)
            root = new Node();
        if (d == key.length())
        {
            root->val = val;
            return root;
        }
            
        root->next[key[d]] = set(root->next[key[d]], key, val, d + 1);
        return root;
    }
public:
    Tries():root(NULL){  }
    int get(string& key)
    {
        Node* ans = get(root, key, 0);
        if (ans == NULL)
            return inf;
        return ans->val;
    }
    void set(string &key, int val)
    {
        root = set(root, key, val, 0);
    }


};

  

字典树(Trie)的基本实现(C++)

标签:blog   io   for   div   sp   log   on   c   amp   

原文地址:http://www.cnblogs.com/xlinc/p/3961489.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!