通过数组的方式记录字符的位置信息,关于 Trie 的应用场景,记住 8 个字:一次建树,多次查询。
private:
bool isEnd;
Trie* next[26];
public:
/** Initialize your data structure here. */
Trie() {
isEnd=false;
memset(next,0,sizeof(next));
}
$$
\TeX
$$
/** Inserts a word into the trie. */
void insert(string word) {
Trie* node=this;
for(auto c:word){
if(node->next[c-'a']==nullptr){
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(char c:word){
if( node->next[c-'a']==nullptr) 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(char c:prefix){
if(node->next[c-'a']==nullptr) return false;
node=node->next[c-'a'];
}
return true;
}
};