Clear and easy to understand cpp


  • 0
    C
            class TrieNode {
            public: 
                bool isKey = false;
                TrieNode* child[26];
            };
    
            class WordDictionary {
            public:
                // Constructor.
                WordDictionary() {
                    root = new TrieNode();
                }
                
                // Adds a word into the data structure.
                void addWord(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 data structure. A word could
                // contain the dot character '.' to represent any one letter.
                bool search(string word) {
                    return query(root, word, 0);
                }
                
            private: 
                TrieNode* root;
                bool query(TrieNode* lastNode, string &s, int i) {
                    if (s[i] != '.') 
                        return lastNode->child[s[i] - 'a'] && (i == s.size() - 1? lastNode->child[s[i] - 'a']->isKey: query(lastNode->child[s[i] - 'a'], s, i + 1));
                    else {
                        for (int j = 0; j < 26; j++) {
                            if (lastNode->child[j] && (i == s.size() - 1? lastNode->child[j]->isKey: query(lastNode->child[j], s, i + 1)))
                                return true;
                        }
                        return false;
                    }
                }
    
            };
    
            // Your WordDictionary object will be instantiated and called as such:
            // WordDictionary wordDictionary;
            // wordDictionary.addWord("word");
            // wordDictionary.search("pattern");

Log in to reply
 

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