leetcode 208. 实现 Trie (前缀树)

139 阅读1分钟

通过数组的方式记录字符的位置信息,关于 Trie 的应用场景,记住 8 个字:一次建树,多次查询。 e3c98484881bd654daa8419bcb0791a2b6f8288b58ef50df70ddaeefc4084f48-file_1575215107950.png

private:
bool isEnd;
Trie* next[26];
public:
    /** Initialize your data structure here. */
    Trie() {
        isEnd=false;
        memset(next,0,sizeof(next));   
    }
    
$$
\TeX
$$
    /** Inserts a word into the trie. */
    void insert(string word) {
        Trie* node=this;
        for(auto c:word){
            if(node->next[c-'a']==nullptr){
                node->next[c-'a']=new Trie();
            }
            node=node->next[c-'a'];
        }
        node->isEnd=true;
    }
    
    /** Returns if the word is in the trie. */
    bool search(string word) {
        Trie* node=this;
      
        for(char c:word){
           if( node->next[c-'a']==nullptr) return false;
           node=node->next[c-'a'];
        }
        return node->isEnd;

     

    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    bool startsWith(string prefix) {
        Trie* node=this;
        for(char c:prefix){
            if(node->next[c-'a']==nullptr) return false;
            node=node->next[c-'a'];
        }
        return true;

    }
};