[LeetCode] Implement Trie

https://leetcode.com/problems/implement-trie-prefix-tree/#/description

实现前缀树。

class TrieNode {
public:
    bool is_word;
    TrieNode* next[26];
    TrieNode() : is_word{false} {
        for (int i = 0; i < 26; ++i) {
            next[i] = NULL;
        }
    }
};

class Trie {
public:
    /** Initialize your data structure here. */
    Trie() {
        root = new TrieNode();
    }
    
    /** Inserts a word into the trie. */
    void insert(string word) {
        if (word.empty()) return;
        TrieNode* p = root;
        for (char c : word) {
            if (!p->next[c-'a']) {
                p->next[c-'a'] = new TrieNode();
            }
            p = p->next[c-'a'];
        }
        p->is_word = true;
    }
    
    /** Returns if the word is in the trie. */
    bool search(string word) {
        if (word.empty()) return false;
        TrieNode* p = root;
        for (char c : word) {
            p = p->next[c-'a'];
            if (!p) return false;
        }
        if (!p->is_word) return false;
        return true;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    bool startsWith(string prefix) {
        if (prefix.empty()) return true;
        TrieNode* p = root;
        for (char c : prefix) {
            p = p->next[c-'a'];
            if (!p) return false;
        }
        return true;
    }

private:
    TrieNode* root;
};

posted @ 2017-06-02 15:40  mioopoi  阅读(124)  评论(0)    收藏  举报