Help-runtime error concise C++ solution


  • 0
    Z

    Can anybody advise why I always get run-time error for search("a")?
    In the process of practicing C++;
    Thanks in advance.
    '''
    class TrieNode {
    public:

    // Initialize your data structure here.
    int count;
    TrieNode* children[26];
    TrieNode() {
        count = 0;
        for(int i = 0; i < 26; i++)
              children[i] = nullptr;
    }
    ~TrieNode() {
        for(int i = 0; i < 26; i++)
            delete children[i];
        delete[] children;
    }
    

    };

    class Trie {
    public:

    Trie() {
        root = new TrieNode();
    }
    
    // Inserts a word into the trie.
    void insert(string word) {
        getNode(word, true);
    }
    
    // Returns if the word is in the trie.
    bool search(string word) {
        TrieNode* tmpPtr = getNode(word, false);
        return (tmpPtr != nullptr) && (tmpPtr->count > 0);
    }
    
    // Returns if there is any word in the trie
    // that starts with the given prefix.
    bool startsWith(string prefix) {
        return getNode(prefix, false) != nullptr;
    }
    
    ~Trie() {
        delete root;
    }
    

    private:

        TrieNode* root;
        TrieNode* getNode(string word, bool creat) {
        TrieNode* cur = root;
    
        for(int i = 0; i < (int)word.size(); i++) {
            int id = word[i] - 'a';
            if(cur->children[id] == nullptr) {
                if(creat)
                    cur->children[id] = new TrieNode();
                else
                    return nullptr;
            }
            cur = cur->children[id];
        }
        
        if(creat)
            cur->count++;
            
        return cur;
    }
    

    };
    '''


  • 0
    Z

    While I have no issues in VS environment.


Log in to reply
 

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