Trie树的结构是每一个节点,下面有26个子节点,开始会有一个根节点,根据字符串的前缀,分别填在后面,为了区分前缀和完整单词,用一个变量标记这个节点是否是结尾。
class Trie {
private:
bool isEnd;
Trie* next[26];
public:
/** 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(auto c:word){
if(node->next[c-'a']==NULL) node->next[c-'a'] = new Trie();
node = node->next[c-'a'];
}
node->isEnd = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
Trie* node = this;
for(auto c:word){
if(node->next[c-'a']==NULL) return false;
node = node->next[c-'a'];
}
return node->isEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
Trie* node = this;
for(auto c:prefix){
if(node->next[c-'a']==NULL) return false;
node = node->next[c-'a'];
}
return true;
}
};