Clean c++ solution


  • 0
    class TrieNode {
    public:
        // Initialize your data structure here.
        TrieNode() {
            
        }
        TrieNode *children[26] = {NULL};
        bool isNode = false;
    };
    
    class Trie {
    public:
        Trie() {
            root = new TrieNode();
        }
    
        // Inserts a word into the trie.
        void insert(string word) {
            TrieNode *current = root;
            for (auto c : word) {
                int index = c - 'a';
                if (current->children[index] == NULL) {
                    current->children[index] = new TrieNode();
                }
                current = current->children[index];
            }
            current->isNode = 1;
        }
        
        bool search(string &word, bool isPrefix) {
            TrieNode *current = root;
            for (auto c : word) {
                int index = c - 'a';
                if (current->children[index] == NULL)
                    return false;
                current = current->children[index];
            }
            return isPrefix || current->isNode; 
        }
    
        // Returns if the word is in the trie.
        bool search(string word) {
            return search(word, false);
        }
    
        // Returns if there is any word in the trie
        // that starts with the given prefix.
        bool startsWith(string prefix) {
            return search(prefix, true);
        }
    
    private:
        TrieNode* root;
    };
    

Log in to reply
 

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