classTrie { public: /** Initialize your data structure here. */ Trie() : isEnd(false), children(26, nullptr) {
}
/** Inserts a word into the trie. */ voidinsert(string word){ Trie* node = this; for (char c : word) { if (node->children[c-'a'] == nullptr) { node->children[c-'a'] = new Trie(); } node = node->children[c-'a']; } node->isEnd = true; }
/** Returns if the word is in the trie. */ boolsearch(string word){ Trie* node = this; for (char c : word) { if (node->children[c-'a'] == nullptr) returnfalse; node = node->children[c-'a']; } return node->isEnd; }
/** Returns if there is any word in the trie that starts with the given prefix. */ boolstartsWith(string prefix){ Trie* node = this; for (char c : prefix) { if (node->children[c-'a'] == nullptr) { returnfalse; } node = node->children[c-'a']; } returntrue; } private: bool isEnd; vector<Trie*> children; };
/** * 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); */