zoukankan      html  css  js  c++  java
  • 实现 Trie (前缀树)

    实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。

    示例:

    Trie trie = new Trie();

    trie.insert("apple");
    trie.search("apple"); // 返回 true
    trie.search("app"); // 返回 false
    trie.startsWith("app"); // 返回 true
    trie.insert("app");
    trie.search("app"); // 返回 true
    说明:

    你可以假设所有的输入都是由小写字母 a-z 构成的。
    保证所有输入均为非空字符串。

    const int MAXN=26;//英文字符个数
    class Trie
    {
    private:
        Trie *next[MAXN];
        bool isEnd=false;
    public:
        /** Initialize your data structure here. */
        Trie()
        {
            isEnd=false;
            memset(next,0,sizeof(next));
        }
        /** Inserts a word into the trie. */
        void insert(string word)
        {
            if(word.empty())
                return ;
    
            Trie *cur=this;//cur初始化当前节点
            for(auto c:word)
            {
                if(cur->next[c-'a']==nullptr)//看当前结点在前缀树中是否存在
                    cur->next[c-'a']=new Trie();
    
                cur=cur->next[c-'a'];//每个结点有个next和isEnd
            }
            cur->isEnd=true;//当前节点已经是一个完整的字符串
            return ;
        }
        /** Returns if the word is in the trie. */
        bool search(string word)
        {
            if(word.empty())
                return false;
    
            Trie *cur=this;
            for(auto c:word)
            {
                if(cur)
                    cur=cur->next[c-'a'];//若c在Trie中不存在,则cur->next[c-'a']为nullptr
            }
            return cur&&cur->isEnd?true:false;//cur不为空且cur指向的结点为一个完整的字符串,则为成功找到
        }
        /** Returns if there is any word in the trie that starts with the given prefix. */
        bool startsWith(string prefix)
        {
            if(prefix.empty())
                return false;
    
            auto cur=this;
            for(auto c:prefix)
            {
                if(cur)
                    cur=cur->next[c-'a'];
            }
            return cur?true:false;
        }
    };
  • 相关阅读:
    Asp.Net多线程用法1
    Asp.Net操作FTP方法
    django 利用PIL 保存图片
    django —— Celery实现异步和定时任务
    豆瓣源安装requirements.txt
    一个有趣的python排序模块:bisect
    Python 多线程
    python list元素为dict时的排序
    python版本坑:md5例子(python2与python3中md5区别)
    单独的 python 脚本文件使用 django 自带的 model
  • 原文地址:https://www.cnblogs.com/tianzeng/p/11565067.html
Copyright © 2011-2022 走看看