/** Initialize your data structure here. */ Trie() { root = Node(); }
/** Inserts a word into the trie. */ voidinsert(string word) { Node *p = &root; for(char c:word){ if(p->next.find(c) == p->next.end()){ p->next[c] = Node(c); } p = &(p->next[c]); } p->end = 1; }
/** Returns if the word is in the trie. */ boolsearch(string word) { Node *p = &root; for(char c:word){ if(p->next.find(c) == p->next.end()) returnfalse; p = &(p->next[c]); } return p->end == 1; }
/** Returns if there is any word in the trie that starts with the given prefix. */ boolstartsWith(string prefix) { Node *p = &root; for(char c:prefix){ if(p->next.find(c) == p->next.end()) returnfalse; p = &(p->next[c]); } returntrue; } }; /** * 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); */