My simple c++ solution


  • 0
    K
    class TrieNode {
    public:
    bool End=false;
    vector<TrieNode *>list;
    // Initialize your data structure here.
    TrieNode() {
        list.resize(26);
    }
     void setEnd(){
        End=true;
    }
    
    
    bool isEnd(){
        return End;
    }
    void put(char ch, TrieNode * node){
        list[ch-'a']=node;
    }
    TrieNode * get(char ch){
        return list[ch-'a'];
    }
    bool contain(char ch){
        //cout << ch << endl;
        return list[ch-'a']!=NULL;
    }
    

    };

    class Trie {
    public:
    Trie() {
        root = new TrieNode();
    }
    
    // Inserts a word into the trie.
    void insert(string word) {
        TrieNode * node=root;
        for(int i=0; i < word.length(); i++){
            char ch=word[i];
            if(!node->contain(ch)){
                node->put(ch, new TrieNode());
               
            }
            node=node->get(ch);
        }
        node->setEnd();
         
    }
    
    // Returns if the word is in the trie.
    bool search(string word) {
       
      TrieNode * node=searchprefix(word);
      return node!=NULL && node->isEnd();
    }
    
    // Returns if there is any word in the trie
    // that starts with the given prefix.
    bool startsWith(string prefix) {
        TrieNode * node=searchprefix(prefix);
        return node!=NULL;
    }
    
    private:
    TrieNode* root;
    TrieNode * searchprefix(string s){
        TrieNode * node=root;
         
        for(int i=0; i < s.length(); i++){
            char ch=s[i];
            if(node->contain(ch))node=node->get(ch);
            else return NULL;
        }
        return node;
    }
    

    };


  • 0
    K

    You don't need the searchprefix function. Just move that code into the search function and make the following alterations:

       bool search(string s) 
       {
               TrieNode * node=root;
               for(int i=0; i < s.length(); i++){
                   char ch=s[i];
                   if(node->contain(ch))node=node->get(ch);
                   else return false; //Changed from return NULL
               }
               return node->isEnd(); //Changed from return node
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.