208. Implement Trie (Prefix Tree)

来源:互联网 发布:中央财经大学数据库 编辑:程序博客网 时间:2024/06/09 20:33

实现一个字典树

要求:

实现插入一个单词,查找一个单词,是否有某个前缀

思路:

不需要查找前缀单词的数目,也不需要删除一个单词。因此实现起来比较简单。字典树节点中只需要设置一个isEnd变量标记单词结束即可。

class TrieNode{    public:    //因为这个题目不需要统计个数,不需要删除单词,所以,只设置结尾标志    TrieNode* next[26];//字典树的主要结构    bool isEnd;//当前节点是否是单词的结尾    TrieNode(bool is=false)    {        memset(next,0,sizeof(next));        isEnd=is;    }    };class Trie {        TrieNode* root;public:    /** Initialize your data structure here. */    Trie() {        root=new TrieNode();    }        /** Inserts a word into the trie. */    void insert(string word) {        if(word.size()==0) return ;        TrieNode* cur=root;        for(int i=0;i<word.size();i++)        {            if(cur->next[word[i]-'a']==nullptr)                cur->next[word[i]-'a']=new TrieNode();            cur=cur->next[word[i]-'a'];        }        cur->isEnd=true;    }        /** Returns if the word is in the trie. */    bool search(string word) {        TrieNode* p=find(word);        if(p==nullptr) return false;        return p->isEnd;    }        /** Returns if there is any word in the trie that starts with the given prefix. */    //不需要返回前缀单词数目    bool startsWith(string prefix) {        TrieNode* p=find(prefix);        return p!=nullptr;    }    TrieNode* find(string s){        TrieNode* p=root;        for(int i=0;i<s.size();i++)        {            if(p->next[s[i]-'a']==nullptr) return nullptr;            p=p->next[s[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); */


原创粉丝点击