用树枝表示字符,用节点记录截止符(判断一个单词是否结尾)
class Trie {
bool isEnd;
Trie* next[26];
public:
Trie() {
this->isEnd = false;
memset(next, 0, sizeof(next));
}
void insert(string word) {
Trie* node = this;
for(char ch: word){
if(node->next[ch-'a']==nullptr){
node->next[ch-'a'] = new Trie();
}
node = node->next[ch-'a'];
}
node->isEnd = true;
}
bool search(string word) {
Trie* node = this;
for(char ch: word){
if(node->next[ch-'a']==nullptr){
return false;
}
else{
node = node->next[ch-'a'];
}
}
return node->isEnd;
}
bool startsWith(string prefix) {
Trie* node = this;
for(char ch: prefix){
if(node->next[ch-'a']==nullptr){
return false;
}
else{
node = node->next[ch-'a'];
}
}
return true;
}
};
|