1、题208:构造前缀树
错误点:为了解决这道题,在内部类中定义了指针数组Node。但是忽略了C++和C语言中,初始化数组的时候并不会清空数组里的内容。这会导致初始化的数组里面全是野指针,而非nullptr。因此在Node的构造函数里应当将Node里的内容全部清除。即 memset(next, 0, sizeof(next));
cpp
class Trie {
private:
class Node{
public:
string s;
Node* next[26];
Node(string s){
this->s=s;
memset(next, 0, sizeof(next)); //!!!
}
};
Node* root;
public:
Trie() {
root=new Node("");
}
void insert(string word) {
Node* p=root;
for(int i=0;i<word.length();i++){
int curIndex=word[i]-'a';
if((p->next)[curIndex]==nullptr){
(p->next)[curIndex]=new Node("");
}
p=(p->next)[curIndex];
}
p->s=word;
}
bool search(string word) {
Node* p=root;
for(int i=0;i<word.length();i++){
int curIndex=word[i]-'a';
if((p->next)[curIndex]==nullptr){
return false;
}
p=(p->next)[curIndex];
}
if(p->s!=word)return false;
return true;
}
bool startsWith(string prefix) {
Node* p=root;
for(int i=0;i<prefix.length();i++){
int curIndex=prefix[i]-'a';
if((p->next)[curIndex]==nullptr){
return false;
}
p=(p->next)[curIndex];
}
return true;
}
};