zoukankan      html  css  js  c++  java
  • 字典树(Trie)的基本实现(C++)

    简要说明一下:

    主要实现了两个操作,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);
        }
    
    
    };
    

      

  • 相关阅读:
    【Python第九篇】异步IO数据库队列缓存
    【Python第八篇】线程、进程及协程
    【Python第七篇】Socket网络编程
    实验五全部代码,ajax请求
    添加员工
    联级选择
    查询,利用jquery选择器
    列表、表格单选框
    注册
    聊天框
  • 原文地址:https://www.cnblogs.com/xlert/p/3961489.html
Copyright © 2011-2022 走看看