1. 程式人生 > >208 Implement Trie (Prefix Tree) 字典樹(前綴樹)

208 Implement Trie (Prefix Tree) 字典樹(前綴樹)

tar ref ems clas next 字典樹 ted imp arc

實現一個 Trie (前綴樹),包含 insert, search, 和 startsWith 這三個方法。
註意:
你可以假設所有的輸入都是小寫字母 a-z。
詳見:https://leetcode.com/problems/implement-trie-prefix-tree/description/

class TrieNode
{
public:
    TrieNode *next[26];
    char c;
    bool isWord;
    TrieNode():isWord(false)
    {
        memset(next,0,sizeof(TrieNode*)*26);
    }
    TrieNode(char _c):c(_c),isWord(false)
    {
        memset(next,0,sizeof(TrieNode*)*26);
    }
};
class Trie {
public:
    /** Initialize your data structure here. */
    Trie() {
        root=new TrieNode();
    }
    
    /** Inserts a word into the trie. */
    void insert(string word) {
        TrieNode *p=root;
        int id;
        for(char c:word)
        {
            id=c-‘a‘;
            if(p->next[id]==nullptr)
            {
                p->next[id]=new TrieNode(c);
            }
            p=p->next[id];
        }
        p->isWord=true;
    }
    
    /** Returns if the word is in the trie. */
    bool search(string word) {
        TrieNode *p=root;
        int id;
        for(char c:word)
        {
            id=c-‘a‘;
            if(p->next[id]==nullptr)
            {
                return false;
            }
            p=p->next[id];
        }
        return p->isWord;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    bool startsWith(string prefix) {
        TrieNode *p=root;
        int id;
        for(char c:prefix)
        {
            id=c-‘a‘;
            if(p->next[id]==nullptr)
            {
                return false;
            }
            p=p->next[id];
        }
        return true;
    }
private:
    TrieNode *root;
};

/**
 * Your Trie object will be instantiated and called as such:
 * Trie obj = new Trie();
 * obj.insert(word);
 * bool param_2 = obj.search(word);
 * bool param_3 = obj.startsWith(prefix);
 */

208 Implement Trie (Prefix Tree) 字典樹(前綴樹)