字典树的应用,用到了模式匹配
    写的时候遇到了很多坑,包括对trie树的板子理解的不太透彻
    另外写的dfs函数应该传引用,这样可以降低复杂度和内存
    image.png

    1. class WordDictionary {
    2. public:
    3. struct Node{
    4. bool is_end;
    5. Node *son[26];
    6. Node(){
    7. is_end = false;
    8. for(int i=0;i<26;i++){
    9. son[i] = NULL;
    10. }
    11. }
    12. }* root;
    13. /** Initialize your data structure here. */
    14. WordDictionary() {
    15. root = new Node();
    16. }
    17. /** Adds a word into the data structure. */
    18. void addWord(string word) {
    19. Node* p = root;
    20. for(auto c:word){
    21. int v = c-'a';
    22. if(p->son[v]==NULL) p->son[v] = new Node();
    23. p = p->son[v];
    24. }
    25. p->is_end = true; // 这里是下一个结点的指针的is_end是true
    26. }
    27. /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
    28. bool search(string word) {
    29. return dfs(word,0,root);
    30. }
    31. bool dfs(string& word,int u,Node*p){
    32. if(u>=word.size()) return p->is_end;
    33. // if(p==NULL) return false;
    34. if(word[u]=='.'){
    35. for(int i=0;i<26;i++){
    36. if(p->son[i]){
    37. if(dfs(word,u+1,p->son[i])) return true;
    38. }
    39. }
    40. return false;
    41. }
    42. else {
    43. int v = word[u]-'a';
    44. if(p->son[v]==NULL) return false;
    45. else return dfs(word,u+1,p->son[v]);
    46. }
    47. return true;
    48. }
    49. };
    50. /**
    51. * Your WordDictionary object will be instantiated and called as such:
    52. * WordDictionary* obj = new WordDictionary();
    53. * obj->addWord(word);
    54. * bool param_2 = obj->search(word);
    55. */