Achieve Trie (Prefix Tree)

Implement a Trie (prefix tree), comprising insert, search, and startsWith these three operations.

Example:

Trie trie = new Trie();

trie.insert ( "Apple");
trie.search ( "Apple"); // Returns to true
trie.search ( "App"); // returns to false
trie.startsWith ( "App"); // Returns to true
Trie. INSERT ( "App");
trie.search ( "App"); // returns true
Description:

You can assume that all inputs are constituted by the lowercase letters az.
To ensure that all inputs are non-empty string.

const int MAXN=26;//英文字符个数
class Trie
{
private:
    Trie *next[MAXN];
    bool isEnd=false;
public:
    /** Initialize your data structure here. */
    Trie()
    {
        isEnd=false;
        memset(next,0,sizeof(next));
    }
    /** Inserts a word into the trie. */
    void insert(string word)
    { 
        IF(word.empty ())
             return ; 

        Trie * = CUR the this ; // CUR initialization root 
        for (Auto C: Word) 
        { 
            IF (cur> Next [the C- ' A ' ] == nullptr a) // see Current if there are nodes in the prefix tree 
            { 
                Trie * node = new new Trie (); 
                CUR -> Next [the C- ' A ' ] = node; 
            } 
            CUR = cur> Next [the C- ' A ' ]; // every nodes and there is a next isEnd 
        }
        CUR -> = isEnd to true ; // current node has a complete string 
        return ; 
    } 
    / * * Returns The IF The Word in IS Trie. * / 
    BOOL Search ( String Word) 
    { 
        IF (word.empty ())
             return  to false ; 

        Trie * = CUR the this ;
         for (c Auto: Word) 
        { 
            IF (CUR) 
                CUR = cur-> next [the C- ' A ' ]; // If c is not present in the Trie, the cur-> next [c-'a '] is nullptr a 
        }
         Return cur && cur> isEnd? To true : false ; // cur is not empty and cur points to the node into a complete string was successfully found 
    }
     / * * Returns IF there IS in the any Word at The Soho starts with that Trie . The prefix GIVEN * / 
    BOOL startsWith ( String prefix) 
    { 
        IF (prefix.empty ())
             return  to false ; 

        Auto CUR = the this ;
         for (Auto C: prefix) 
        { 
            IF (CUR) 
                CUR = cur> Next [the C- ' A ' ]; 
        } 
        return cur?true:false;
    }
};

 

Guess you like

Origin www.cnblogs.com/tianzeng/p/11565067.html