Implement Trie (Prefix Tree)

来源:互联网 发布:mac 压缩文件夹 编辑:程序博客网 时间:2024/05/17 06:20

原题地址:点我传送

思路是这样的:设计一个这样的结构体,一个节点有26个指向其他节点的指针,同时有一个值记录这个节点是否是按这个字符串查找下来的最后一个值。加入字符串时将每个字符串从头开始,根节点的第(字符-‘a’)个指针指向了一个新的节点,以此类推,最后那个节点设置记录值。搜索时也是如此,从头开始,如果这个指针不为空,则往下按字符查找,查找到最后的那个节点要有记录值才是查找成功。

C++:

class MYCHAR{public:    bool used;    MYCHAR* next[26];    MYCHAR()    {        used = false;        memset(next, NULL, sizeof(MYCHAR*) * 26);    }};class WordDictionary {public:    /** Initialize your data structure here. */    WordDictionary() {        root = new MYCHAR();    }        /** Adds a word into the data structure. */    void addWord(string word) {        MYCHAR*  temp = root;        for(int i=0;i<word.length();i++)        {            if(!(temp->next[word[i]-'a']))            {                temp->next[word[i]-'a'] = new MYCHAR();            }            temp=temp->next[word[i]-'a'];        }        temp->used=true;        return;    }        /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */    bool search(string word) {        return SEARCH(word,root);    }    bool SEARCH(string s,MYCHAR* node)    {        MYCHAR* temp = node;        for(int i=0;i<s.length();i++)        {            if(temp)            {                if(s[i]!='.')                {                    temp = temp->next[s[i]-'a'];                }                else                {                    MYCHAR* TEMP = temp;                    for(int j=0;j<26;j++)                    {                        temp = TEMP->next[j];                        if(SEARCH(s.substr(i+1),temp))                        {                            return true;                        }                    }                }            }            else break;        }        return temp&&temp->used;    }private:    MYCHAR* root;};/** * Your WordDictionary object will be instantiated and called as such: * WordDictionary obj = new WordDictionary(); * obj.addWord(word); * bool param_2 = obj.search(word); */