
变量简洁正确完整思路 字典树,查找用dfs,形参beg,word,root,判断root树是否有beg为开始下标的word,如果root树为空边界返回false,如果beg==n则边界返回root->isEnd,最后返回,如果是。则26个只要有一个dfs得出root->next树有以beg+1的就是root树有,返回true,否则26都没有返回false,或者是字母,dfs判断root->next[word[beg]-'a']这棵树是否有 class WordDictionary { public: WordDictionary() { isEnd=false; memset(next,0,sizeof(next)); } void addWord(string word) { WordDictionary*node=this; for(char c:word){ if(!node->next[c-'a'])node->next[c-'a']=new WordDictionary(); node=node->next[c-'a']; } node->isEnd=true; } bool search(string word) { return dfs(0,word,this); } bool dfs(int beg,string&word,WordDictionary*root){ if(!root)return false; if(beg==word.size())return root->isEnd; if(word[beg]=='.'){ for(int i=0;i<26;i++){ if(dfs(beg+1,word,root->next[i]))return true; } return false; }else return dfs(beg+1,word,root->next[word[beg]-'a']); } private: bool isEnd; WordDictionary*next[26]; }; 踩过的坑 if(beg==word.size())return root->isEnd; mmd,这里是root->isEnd,是root树的,不是this->isEnd,root树是this树的子树 字典树当前节点是没有字母的,也就是说不用判断的,字母在箭头上,只需要dfs找到 字母对应的箭头来比较就可以形成递归
浙公网安备 33010602011771号