208. Implement Trie

来源:互联网 发布:广州网络危机公关公司 编辑:程序博客网 时间:2024/05/20 12:24
class TrieNode {public:    TrieNode *next[26];    bool isword;    // Initialize your data structure here.    TrieNode(bool b=false) {        isword=b;        memset(next,0,sizeof(next));    }};class Trie {public:    Trie() {        root = new TrieNode(false);    }    // Inserts a word into the trie.    void insert(string word) {        TrieNode *p=root;        int n=word.size();        for(int i=0;i<n;i++)        {            if(p->next[word[i]-'a']==NULL)                p->next[word[i]-'a']=new TrieNode(false);            p=p->next[word[i]-'a'];        }        p->isword=true;    }    // Returns if the word is in the trie.    bool search(string word) {        TrieNode *p=find(word);        if(p!=NULL&&p->isword)            return true;        else            return false;    }    // Returns if there is any word in the trie    // that starts with the given prefix.    bool startsWith(string prefix) {        return find(prefix)!=NULL;    }private:    TrieNode *find(string word)    {        TrieNode *p=root;        int n=word.size();        for(int i=0;i<n&&p!=NULL;i++)        {            p=p->next[word[i]-'a'];        }        return p;    }    TrieNode* root;};
1 0
原创粉丝点击