创建字典树
class Trie {
private:
vector<Trie*> children;
bool isEnd;
public:
/** Initialize your data structure here. */
Trie() : children(26), isEnd(false) {}
/** Inserts a word into the trie. */
void insert(string word) {
Trie * node = this;
for(auto ch:word){
int i = ch - 'a';
if(node->children[i]==NULL){
node->children[i] = new Trie();
}
node = node->children[i];
}
node->isEnd = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
Trie * node = this;
for(auto ch:word){
int i = ch - 'a';
if(node->children[i]==NULL){
return false;
}
node = node->children[i];
}
if(node->isEnd){
return true;
}
return false;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
Trie * node = this;
for(auto ch:prefix){
int i = ch - 'a';
if(node->children[i]==NULL){
return false;
}
node = node->children[i];
}
return true;
}
};