美文网首页
Leetcode 208:Implement Trie (Pre

Leetcode 208:Implement Trie (Pre

作者: Jesson3264 | 来源:发表于2018-05-13 22:45 被阅读0次

    题目链接:
    https://leetcode.com/problems/implement-trie-prefix-tree/description/

    字典树,常见到操作,插入,查找,是否是前缀。
    参考的一段代码:

    #include <iostream>
    
    using namespace std;
    
    class Trie{
        public:
        struct TrieNode
        {
            int cnt;
            TrieNode *next[26];//a-z
            bool isword;
            TrieNode()
            {
                cnt = 0;
                isword = false;
                for(int i=0; i<26; ++i)
                    next[i] = NULL;
            }  
        };
        
        TrieNode *root;
        Trie()
        {
            root = new TrieNode();
        }
        void insert(string word)
        {
            int slen = word.length();
            TrieNode *p = root;
            for(int i=0; i<slen; ++i)
            {
                int cindex = word[i]-'a';
                if(NULL==p->next[cindex])
                {
                    TrieNode *tnode = new TrieNode();
                    tnode->cnt = 1;
                    p->next[cindex]= tnode;
                    p = tnode;
                }
                else
                {
                    p->next[cindex]->cnt += 1;
                    p = p->next[cindex];
                }
            } 
            p->isword = true;
        }
    
        bool search(string word)
        {
            int slen = word.length();
            TrieNode *p = root; 
            int i = 0;
            for(; i<slen; ++i)
            {
                int sindex = word[i]-'a';
                if(NULL==p->next[sindex]) 
                    break;
                p = p->next[sindex];
            }
            if (i==slen)
                return (p->isword);
            return false; 
        }
    
        bool startsWith(string prefix)
        {
            int slen = prefix.length();
            int i = 0; 
            TrieNode *p = root;
            for(;i<slen; ++i)
            {
                if(NULL==p->next[prefix[i]-'a'])
                    break;       
                p = p->next[prefix[i]-'a'];
            }
            if(i!=slen)
                return false;
            return true;        
        }
        
    };
    int main(int argc, char **argv)
    {
        Trie obj = Trie();
        string word;
        word = "Trie"; 
        obj.insert(word);
        word = "insert"; 
        obj.insert(word);
        word = "search"; 
        obj.insert(word);
        word = "startsWith"; 
        obj.insert(word);
        word = "a"; 
        cout<<obj.search(word)<<endl;
        cout<<obj.startsWith(word)<<endl;
        return 0;
    }
    
    
    

    相关文章

      网友评论

          本文标题:Leetcode 208:Implement Trie (Pre

          本文链接:https://www.haomeiwen.com/subject/rjyrdftx.html