• 实现 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;
        }
    };
  • 相关阅读:
    explain组合索引是否命中
    高并发优化
    docker基础篇一
    Web API 集成Serilog
    复习一下CSS,做笔记记录一下
    Process调用winform程序
    winform自动更新
    格式化xml 给没有节点的内容添加节点
    2.Grpc消息定义
    1.Grpc环境配置
  • 原文地址:https://www.cnblogs.com/tianzeng/p/11565067.html
Copyright © 2020-2023  润新知