Clear and easy understand cpp


  • 0
    C
        class TrieNode {
        public:
            bool isKey = false;
            TrieNode* child[26];
        };
    
        class Trie {
        public:
            Trie() {
                root = new TrieNode();
            }
    
            // Inserts a word into the trie.
            void insert(string word) {
                TrieNode* lastNode = root;
                for (char c: word) {
                    if (!lastNode->child[c - 'a'])
                        lastNode->child[c - 'a'] = new TrieNode();
                    lastNode = lastNode->child[c - 'a'];
                }
                lastNode->isKey = true;
            }
    
            // Returns if the word is in the trie.
            bool search(string word) {
                TrieNode* lastNode = root;
                return query(lastNode, word) && lastNode->isKey;
            }
    
            // Returns if there is any word in the trie
            // that starts with the given prefix.
            bool startsWith(string prefix) {
                TrieNode* lastNode = root;
                return query(lastNode, prefix);
            }
    
        private:
            TrieNode* root;
            bool query(TrieNode* &lastNode, string word) {
                for (char c: word) {
                    if (!lastNode->child[c - 'a'])
                        return false;
                    lastNode = lastNode->child[c - 'a'];
                }
                return true;
            }
        };

Log in to reply
 

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