You may assume that all inputs are consist of lowercase letters a-z.
All inputs are guaranteed to be non-empty strings.
class Trie {
public:
class TrieNode {
public:
vector<TrieNode*> next;
bool isWord;
TrieNode() : next(vector<TrieNode*>(26, nullptr)), isWord(false) {}
~TrieNode() {
for (TrieNode*& ptr : next) {
if (ptr) delete ptr;
}
}
};
/** Initialize your data structure here. */
Trie() {
root = new TrieNode();
}
~Trie() {
delete root;
}
/** Inserts a word into the trie. */
void insert(string word) {
TrieNode* cur = root;
for (char ch : word) {
if (!cur->next[ch - 'a']) {
cur->next[ch - 'a'] = new TrieNode();
}
cur = cur->next[ch - 'a'];
}
cur->isWord = true;
}
TrieNode* find(string target) {
TrieNode* cur = root;
for (char ch : target) {
if (!cur->next[ch - 'a']) return nullptr;
cur = cur->next[ch - 'a'];
}
return cur;
}
/** Returns if the word is in the trie. */
bool search(string word) {
TrieNode* cur = find(word);
return cur && cur->isWord;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
return find(prefix) != nullptr;
}
private:
TrieNode* root;
};