Tire树(字典树、前缀树)的简介和构造

来源:互联网 发布:火炬之光2mac 编辑:程序博客网 时间:2024/06/08 07:51

先留着填个坑,免得哪天忘记写了。。。
先把代码写下,注释以后再补,现在在等offer心焦中

namespace CjpSTL{    class Trie    {        struct Node;        using NodePtr = Node*;        struct Node        {            unordered_map<char, NodePtr> dict;            char ch;            bool hasVal;            int count;            Node(char _ch) :ch(_ch), dict(), count(1), hasVal(false) {}        };    public:        Trie();        void add(const string& str) const        {            auto cur = root;            for (auto ch : str)            {                auto des = cur->dict.find(ch);                if (des != cur->dict.end())                {                    ++cur->dict[ch]->count;                    cur = cur->dict[ch];                }                else                {                    cur->dict[ch] = new Node(ch);                    cur = cur->dict[ch];                }            }            cur->hasVal = true;        }        bool find(const string& str)const        {            auto cur = root;            for (auto ch : str)            {                auto des = cur->dict.find(ch);                if (des != cur->dict.end())                {                    cur = cur->dict[ch];                    ++cur->count;                }                else                {                    return false;                }            }            return cur->hasVal;        }        void erase(const string& str)const        {            auto cur = root;            auto pre = root;            for (auto ch : str)            {                auto des = cur->dict.find(ch);                if (des != cur->dict.end())                {                    pre = cur;                    cur = cur->dict[ch];                    --cur->count;                }                else                {                    break;                }            }            cur->hasVal = false;        }        ~Trie();    private:        NodePtr root = new Node('\0');    };}