A trie (pronounced as “try”) or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.
Implement the Trie class:
Trie() Initializes the trie object.
void insert(String word) Inserts the string word into the trie.
boolean search(String word) Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise.
boolean startsWith(String prefix) Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise.
classTrie { _Trie* trie; public: /** Initialize your data structure here. */ Trie() { this->trie = new _Trie(); }
/** Inserts a word into the trie. */ voidinsert(string word){ _Trie* cur = trie; for(int i = 0; i < word.size(); i++) { cur = cur->insertIfAbsence(word[i]); } cur->eow(); }
/** Returns if the word is in the trie. */ boolsearch(string word){ _Trie* cur = trie; for(int i = 0; i < word.size() && cur; i++) { cur = cur->get(word[i]); } return cur && cur->getEow(); }
/** Returns if there is any word in the trie that starts with the given prefix. */ boolstartsWith(string prefix){ _Trie* cur = trie; for(int i = 0; i < prefix.size() && cur; i++) { cur = cur->get(prefix[i]); } return cur; } };
/** * 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); */