//slower than recursive version
class Trie {
private:
static constexpr int R = 26;
struct Node {
bool is_word = false;
Node *next = nullptr;
};
public:
//~Trie(); How to write efficient dectructor?
void insert(string word) {
if (word.empty()) return;
Node *x = &root;
int p = 0;
while (p < word.size()) {
if (!x->next) x->next = new Node[R];
x = &x->next[word[p++] - 'a'];
}
x->is_word = true;
}
bool search(string word) {
Node x = root;
int p = 0;
while (x.next && p < word.size())
x = x.next[word[p++] - 'a'];
return p == word.size() && x.is_word;
}
bool startsWith(string prefix) {
Node x = root;
int p = 0;
while (x.next && p < prefix.size())
x = x.next[prefix[p++] - 'a'];
return p == prefix.size() && (x.next || x.is_word);
}
private:
Node root;
};