struct Node {
bool isWord = false;
Node* child[26] = {};
};
class Trie {
public:
Node* root;
/** Initialize your data structure here. */
Trie() {
root = new Node();
}
/** Inserts a word into the trie. */
void insert(string word)
{
//使用字典树
int len = word.size();
Node* node = root;
for (int i = 0; i < len; ++i)
{
char c = word[i];
if (node->child[c - 'a'] == NULL)
{
node->child[c - 'a'] = new Node();
}
node = node->child[c - 'a'];
}
node->isWord = true;
}
/** Returns if the word is in the trie. */
bool search(string word)
{
int len = word.size();
Node* t = root;
for (int i = 0; i < len&&t; ++i)
{
char c = word[i];
t = t->child[c - 'a'];
}
return t != NULL&&t->isWord;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix)
{
int len = prefix.size();
Node* t = root;
for (int i = 0; i < len&&t; ++i)
{
char c = prefix[i];
t = t->child[c - 'a'];
}
return t != NULL;
}
};
/**
* 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);
*/