欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode 208. 实现 Trie (前缀树)

程序员文章站 2022-07-15 16:17:37
...

原题目:https://leetcode-cn.com/problems/implement-trie-prefix-tree/

 

思路:

看一下youtube上的视频:视频

举个栗子:see,sells,she

LeetCode 208. 实现 Trie (前缀树)

 

 

代码:

class Trie {
private:
    bool isEnd;
    Trie* next[26];
public:
    /** Initialize your data structure here. */
    Trie() {
        isEnd = false;
        memset(next,0,sizeof(next));
    }
    
    /** Inserts a word into the trie. */
    void insert(string word) {
        auto node = this;
        for(char& c: word){
            if(node->next[c-'a']==NULL){
                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) {
        auto node = this;
        for(char& c: word){
            node = node->next[c-'a'];
            if(node==NULL) return false;
        }
        return node->isEnd;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    bool startsWith(string prefix) {
        auto node = this;
        for(char& c:prefix){
            node = node->next[c-'a'];
            if(node==NULL) return false;
        }
        return true;
    }
};