class Trie {
private:
vector<Trie*>children; //每个节点包括一个指针数组和一个结束标记
bool isend;
Trie* searchPrefix(string prefix){ //返回该前缀最远走到的地方
Trie* node=this;
for(char c:prefix){
if(!node->children[c-'a'])return nullptr;
node=node->children[c-'a'];
}
return node;
}
public:
Trie() {
children.resize(26);
isend=false;
}
void insert(string word) {
Trie* node=this; //插入单词,如果走到某个地方为空,就新建Node
for(char c:word){
if(node->children[c-'a']==nullptr)node->children[c-'a']=new Trie();
node=node->children[c-'a'];
}
node->isend=true;
}
bool search(string word) { //最后到达地方不为空且结束标记为true
Trie* node=searchPrefix(word);
return node!=nullptr&&node->isend;
}
bool startsWith(string prefix) { //最后到达地方不为空
return searchPrefix(prefix)!=nullptr;
}
};
字典树板zi
最新推荐文章于 2024-06-13 10:05:06 发布