208. Implement Trie (Prefix Tree)

来源:互联网 发布:杭州博远软件 编辑:程序博客网 时间:2024/05/24 02:57

这道题是要求完成一个字典树。

例如,一个保存了8个键的trie结构,"A", "to", "tea", "ted", "ten", "i", "in", and "inn".如下图所示:

首先设计树的结点,每个结点有26个子结点。isWord表示这个结点是单词还是前缀。就是每次插入单词的时候,插入到最后一个字符之后把这个结点的isWord设为true即可。

class TrieNode{public:    TrieNode *child[26];    bool isWord;    TrieNode() : isWord(false){        for(auto &a : child)            a = NULL;    }};class Trie {    TrieNode* root;public:    /** Initialize your data structure here. */    Trie() {        root = new TrieNode();    }        /** Inserts a word into the trie. */    void insert(string word) {        TrieNode *p = root;        for(auto &a : word){            int i = a - 'a';            if(!p->child[i])                p->child[i] = new TrieNode();            p = p->child[i];        }        p->isWord = true;    }        /** Returns if the word is in the trie. */    bool search(string word) {        TrieNode *p = root;        for(auto &a : word){            int i = a - 'a';            if(!p->child[i])    return false;            p = p->child[i];        }        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;        for(auto &a : prefix){            int i = a - 'a';            if(!p->child[i])                return false;            p = p->child[i];        }        return true;    }};/** * 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); */


原创粉丝点击