struct TrirNode{
string word;
unordered_map<char,TrirNode*> children;
TrirNode(){
this->word="";
}
};
class Trie {
public:
TrirNode* root;
Trie() {
root=new TrirNode();
}
void insert(string word) {
TrirNode* node=root;
for(char ch:word)
{
if(!node->children.count(ch)) node->children[ch]=new TrirNode();
node=node->children[ch];
}
node->word=word;
}
bool search(string word) {
TrirNode* node=root;
for(char ch:word)
{
if(!node->children.count(ch)) return false;
node=node->children[ch];
}
if(node->word==word) return true;
return false;
}
bool startsWith(string prefix) {
TrirNode* node=root;
for(char ch:prefix)
{
if(!node->children.count(ch)) return false;
node=node->children[ch];
}
return true;
}
};
前缀树:通过构造字符对应的树结构查询字符串是否存在
图示:假如我们插入"apple""banana""pear"前缀树长什么样呢?

查询,插入自然形成了类似的树结构,沿着孩子链一路遍历就是精髓
1451

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



