字典树(Trie Tree)
图片来源.
class Trie {
public:
bool isEnd;
Trie* next[26];
/** Initialize your data structure here. */
Trie() {
isEnd = false;
memset(next,0,sizeof(next));
}
/** Inserts a word into the trie. */
void insert(string word) {
Trie* node = this ;
for(char ch:word){
ch -= 'a';
if(node->next[ch] == nullptr)
{
node->next[ch] = new Trie();
}
node = node -> next[ch];
}
node -> isEnd = true;
}
Trie* searchPre(string prefix){
Trie* node = this;
for(char ch:prefix){
ch -= 'a';
if(node->next[ch] == nullptr){
return nullptr;
}
node = node->next[ch];
}
return node;
}
/** Returns if the word is in the trie. */
bool search(string word) {
Trie* node = searchPre(word);
if(node == nullptr || node->isEnd == false )
return false;
return true;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
Trie* node = searchPre(prefix);
if(node == nullptr)
return false;
return true;
}
};