实现 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)//看当前结点在前缀树中是否存在
            {
                Trie *node=new Trie();
                cur->next[c-'a']=node;
            }
            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;
    }
};

猜你喜欢

转载自www.cnblogs.com/tianzeng/p/11565067.html