前缀树(Trie)

3 分钟阅读 503 词
cpp
class Trie {
public:
vector<Trie*> children;
bool isEnd;
    Trie() 
    :children(26)
    ,isEnd(false)
    {

    }
    Trie * searchPrefix(string prefix){
        Trie * node =this;
        for(char ch:prefix){
            ch-='a';
            if(node->children[ch]==nullptr){
                return nullptr;
            }
            node =node->children[ch];
        }
        return node;
    }

    void insert(string word) {
        Trie * node =this;
        for(char ch:word){
            ch -='a';
            if(node->children[ch]==nullptr){
                node->children[ch]=new Trie();
            }
            node = node->children[ch];
        }
        node->isEnd=true;;
    }
    
    bool search(string word) {
        Trie * node =this->searchPrefix(word);
        return node !=nullptr&&node->isEnd;
    }
    
    bool startsWith(string prefix) {
        Trie * node = searchPrefix(prefix);
        return node!=nullptr;
    }
};

目录