实现一个Trie树
一、Trie树的基本操作
(1) 插入字符串
(2) 搜索目标字符串
(3) 搜索以目标字符串为前缀的情况是否存在
二、代码实现
class Trie{
public:
class TrieNode{
public:
TireNode(char data){
this->data = data;
this->children.assign(26, nullptr);
}
public:
char data;
bool isEnding = false;
vector<TireNode*> children;
};
public:
Tire(){
root = new TrieNode('/');
}
void insert(string word){
TrieNode* p = root;
for(int i = 0; i < word.size(); ++i){
char c = word[i];
if(p->children[c - 'a'] == nullptr)
p->childrem[c - 'a'] = new TrieNode(c);
p = p->children[c - 'a'];
}
p->isEnding = true;
}
bool search(string word){
TrieNode* p = root;
for(int i = 0; i < word.size(); ++i){
char c = word[i];
if(p->children[c - 'a'] == nullptr)
return false;
p = p->children[c - 'a'];
}
return p->isEnding;
}
bool startsWith(string prefix){
TrieNode* p = root;
for(int i = 0; i < prefix.size(); ++i){
char c = prefix[i];
if(p->children[c - 'a'] == nullptr)
return false;
p = p->children[c - 'a'];
}
return true;
}
public:
TireNode* root;
};