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);
        }
    
    
    };
    

      

  • 相关阅读:
    DotnetCore 单文件发布
    Parallel.ForEach 之 MaxDegreeOfParallelism
    Quartznet速记
    C# SendAysnc 超时
    微耕门禁跨网段搜索代理
    服务守护DOS脚本
    Flutter速记
    ShowDoc速记
    Docker运行dotnetcore
    Redis速记
  • 原文地址:https://www.cnblogs.com/xlert/p/3961489.html
Copyright © 2011-2022 走看看