Advertisement
Guest User

Untitled

a guest
Nov 21st, 2019
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.78 KB | None | 0 0
  1. class WordDictionary {
  2. public:
  3.     struct node
  4.     {
  5.         int val;
  6.         node *v[26];
  7.         node()
  8.         {
  9.             val = 0;
  10.             for(int i=0; i<26; ++i)
  11.                 v[i]=NULL;
  12.         }
  13.     };
  14.    
  15.     node *root;
  16.    
  17.    
  18.     /** Initialize your data structure here. */
  19.     WordDictionary() {
  20.         root = new node;
  21.     }
  22.    
  23.     /** Adds a word into the data structure. */
  24.     void addWord(string word) {
  25.         add(root, word, 0);
  26.     }
  27.    
  28.     void add(node *&root, string &word, int k)
  29.     {
  30.         if(k==word.length())
  31.             root->val++;
  32.         else
  33.         {
  34.             if(root->v[word[k]-'a']==NULL)
  35.                 root->v[word[k]-'a'] = new node;
  36.             add(root->v[word[k]-'a'], word, k+1);
  37.         }
  38.     }
  39.    
  40.     /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
  41.     bool search(string word) {
  42.         return query(root, word, 0);
  43.     }
  44.    
  45.     bool query(node *&root, string &word, int k)
  46.     {
  47.         if(k==word.length())
  48.             return root->val;
  49.         else
  50.         {
  51.             if(word[k]=='.')
  52.             {
  53.                 bool ok=0;
  54.                 for(int i=0; i<26; ++i)
  55.                     if(root->v[i]!=NULL)
  56.                         ok|=query(root->v[i], word, k+1);
  57.                 return ok;
  58.             }
  59.             else
  60.             {
  61.                 if(root->v[word[k]-'a']!=NULL)
  62.                     return query(root->v[word[k]-'a'], word, k+1);
  63.                 return 0;
  64.             }
  65.         }
  66.     }
  67. };
  68.  
  69. /**
  70.  * Your WordDictionary object will be instantiated and called as such:
  71.  * WordDictionary* obj = new WordDictionary();
  72.  * obj->addWord(word);
  73.  * bool param_2 = obj->search(word);
  74.  */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement