思想:字典树 我的代码
struct TreeNodes{
vector<TreeNodes *>node;
bool isEnd;
TreeNodes(){
this->node=vector<TreeNodes *>(26,nullptr);
this->isEnd=false;
}
};
void insert(TreeNodes *root,const string &words){
TreeNodes *p=root;
for(char a:words){
if(p->node[a-'a']==nullptr)
p->node[a-'a']=new TreeNodes();
p=p->node[a-'a'];
}
p->isEnd=true;
}
class WordDictionary {
private:
TreeNodes* root;
public:
WordDictionary() {
root=new TreeNodes();
}
void addWord(string word) {
insert(root,word);
}
bool search(string word) {
return dfs(root,0,word);
}
bool dfs(TreeNodes *root,int i,const string &words){
if(i==words.size())
return root->isEnd;
if(words[i]>='a'&&words[i]<='z'){
if(root->node[words[i]-'a']!=nullptr&&dfs(root->node[words[i]-'a'],i++,words))
return true;
}
else if(words[i]=='.'){
for(int ii=1;ii<=26;++ii){
if(root->node[words[i]-'a']!=nullptr&&dfs(root->node[words[i]-'a'],i++,words))
return true;
}
}
return false;
}
};
问题:在使用search的时候,dfs进行第一次迭代时,输入的root变成了NULL 解决:将dfs改为 注:虽然解决了,但是为啥会这样啊????
bool dfs(TreeNodes* root, int i, const string& words) {
if (i == words.size())
return root->isEnd;
TreeNodes* p;
if (words[i] >= 'a' && words[i] <= 'z') {
p = root->node[words[i] - 'a'];
if (p!= nullptr && dfs(p, ++i, words))
return true;
}
else if (words[i] == '.') {
for (int ii = 0; ii <= 25; ++ii) {
p = root->node[ii];
if (p!= nullptr && dfs(p, ++i, words))
return true;
}
}
return false;
}
然后发现在else后,使用++i会导致每次for循环都给i+1 解决:++i改为i+1
|