字典树的应用,用到了模式匹配
写的时候遇到了很多坑,包括对trie树的板子理解的不太透彻
另外写的dfs函数应该传引用,这样可以降低复杂度和内存
class WordDictionary {public:struct Node{bool is_end;Node *son[26];Node(){is_end = false;for(int i=0;i<26;i++){son[i] = NULL;}}}* root;/** Initialize your data structure here. */WordDictionary() {root = new Node();}/** Adds a word into the data structure. */void addWord(string word) {Node* p = root;for(auto c:word){int v = c-'a';if(p->son[v]==NULL) p->son[v] = new Node();p = p->son[v];}p->is_end = true; // 这里是下一个结点的指针的is_end是true}/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */bool search(string word) {return dfs(word,0,root);}bool dfs(string& word,int u,Node*p){if(u>=word.size()) return p->is_end;// if(p==NULL) return false;if(word[u]=='.'){for(int i=0;i<26;i++){if(p->son[i]){if(dfs(word,u+1,p->son[i])) return true;}}return false;}else {int v = word[u]-'a';if(p->son[v]==NULL) return false;else return dfs(word,u+1,p->son[v]);}return true;}};/*** Your WordDictionary object will be instantiated and called as such:* WordDictionary* obj = new WordDictionary();* obj->addWord(word);* bool param_2 = obj->search(word);*/
