
构建一颗自动树的代码模板
class Trie {
public:
// 利用this 的特性在当前类上直接构建一颗 字典树
//字典树 多叉树-》要用到指针数组来存储子树根节点
vector<Trie*> children;//C++ 会自动将字符初始化为空指针
bool isend;
Trie():children(26),isend(false) {
}
Trie * searchPrefix(string prefix){
Trie * node=this;
for(auto i:prefix){
i-='a';
if(node->children[i]==nullptr){
return nullptr;
}
node=node->children[i];//迭代法查找多叉映射树
}
return node;
}
void insert(string word) {
Trie * node=this;
for(auto i:word){
i-='a';
if(node->children[i]==nullptr){
node->children[i]=new Trie();//new Trie();C++ 允许的写法 分配一Trie 大小的空间 并且调用构造函数 对其进行初始化
}
node=node->children[i];
}
node->isend=true;
}
bool search(string word) {
Trie *node =this->searchPrefix(word);
return node!=nullptr&&node->isend;
}
bool startsWith(string prefix) {
return this->searchPrefix(prefix)!=nullptr;
}
};
1173

被折叠的 条评论
为什么被折叠?



