208. Implement Trie (Prefix Tree)

来源:互联网 发布:mac 简体双拼输入法 编辑:程序博客网 时间:2024/06/06 11:03

Implement a trie with insert, search, and startsWith methods.

trie是一棵树,用于存储字符串的,有公共前缀的字符串在一棵子树上。

class TrieNode{    public:    TrieNode* next[26];    bool is_word;        TrieNode(bool b=false){        memset(next, 0, sizeof(next));        is_word=b;    }        ~TrieNode(){}};class Trie {public:    TrieNode* root;    /** Initialize your data structure here. */    Trie() {        root=new TrieNode();    }        /** Inserts a word into the trie. */    void insert(string word) {                TrieNode *p=root;        for(int i=0; i<word.size(); ++i){            if(p->next[word[i]-'a']==NULL) p->next[word[i]-'a']=new TrieNode();            p=p->next[word[i]-'a'];        }        p->is_word=true;            }        /** Returns if the word is in the trie. */    bool search(string word) {        TrieNode* p=find(word);                return p!=NULL&&p->is_word;    }        /** Returns if there is any word in the trie that starts with the given prefix. */    bool startsWith(string prefix) {                return find(prefix)!=NULL;    }        ~Trie(){delete root;}    private:        TrieNode* find(string word){        TrieNode *p=root;        for(int i=0; i<word.size()&&p!=NULL; ++i) p=p->next[word[i]-'a'];                return p;    }};/** * 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); */


0 0
原创粉丝点击