public: /** Initialize your data structure here. */ Trie() : children(26), isEnd(false) {} /** Inserts a word into the trie. */ voidinsert(string word){ Trie* node = this; for(char c : word) { c -= 'a'; if(node->children[c] == nullptr) { node->children[c] = newTrie(); } node = node->children[c]; } node->isEnd = true; } /** Returns if the word is in the trie. */ boolsearch(string word){ Trie* node = this->searchPrefix(word); return node != nullptr && node->isEnd; } /** Returns if there is any word in the trie that starts with the given prefix. */ boolstartsWith(string prefix){ returnthis->searchPrefix(prefix) != nullptr; } };
/** * Your Trie object will be instantiated and called as such: * Trie* obj = new Trie(); * obj->insert(word); * bool param_2 = obj->search(word); * bool param_3 = obj->startsWith(prefix); */