LeetCode系列208—实现Trie (前缀树)

题意

208. 实现 Trie (前缀树)

题解

方法一:字典树

Trie,又称前缀树或字典树

class Trie {
    
    
private:
    vector<Trie*> children;
    bool isEnd;

    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;
    }

public:
    Trie() : children(26), isEnd(false) {
    
    }

    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) {
    
    
        return this->searchPrefix(prefix) != nullptr;
    }
};

参考

实现 Trie (前缀树)

Guess you like

Origin blog.csdn.net/younothings/article/details/120225809