概述:
211简化版,简单插入和搜索判断就好
代码:
class Trie {
public:
//定义前缀树结构体
struct TrieNode{
bool isEnd = false;
TrieNode* children[26] = {NULL};
};
//构造函数
Trie(): root(new TrieNode){}
void insert(string word) {
//从根开始插入
auto p = root;
for(int i = 0; i < word.size(); i++){
int idx = word[i] - 'a';
if(p->children[idx] == NULL)
p->children[idx] = new TrieNode;
p = p->children[idx];
}
p->isEnd = true;
}
bool search(string word) {
auto p = root;
for(int i = 0; i < word.size(); i++){
int idx = word[i] - 'a';
if(p->children[idx] == NULL) return false;
p = p->children[idx];
}
return p->isEnd;
}
bool startsWith(string prefix) {
auto p = root;
for(int i = 0; i < prefix.size(); i++){
int idx = prefix[i] - 'a';
if(p->children[idx] == NULL) return false;
p = p->children[idx];
}
return true;
}
private:
TrieNode* root;
};
/**
* Your Trie object will be instantiated and called as such:
* Trie* obj = new Trie();
* obj->insert(word);
* bool param_2 = obj->search(word);
* bool param_3 = obj->startsWith(prefix);
*/