Leetcode 208:Implement Trie (Prefix Tree)

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

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

#include 

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; inext[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(; inext[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(;inext[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<

你可能感兴趣的:(Leetcode 208:Implement Trie (Prefix Tree))