jayati

Design Add and Search Words Data Structure

Mar 18th, 2023
240
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.29 KB | None | 0 0
  1. class TrieNode{
  2. public:
  3.     TrieNode *child[26];
  4.     bool end = false;
  5.     TrieNode(){
  6.         for(int i = 0; i < 26; i++)
  7.             child[i] = NULL;
  8.     }
  9. };
  10. class WordDictionary {
  11.       TrieNode *root ;
  12. public:
  13.     WordDictionary() {
  14.         root =  new TrieNode();
  15.     }
  16.    
  17.     void addWord(string word) {
  18.         int idx = 0;
  19.         TrieNode * node = root;
  20.         for(char c: word) {
  21.             idx = c -'a';
  22.             if(!node->child[idx])
  23.                 node->child[idx] = new TrieNode();
  24.             node = node->child[idx];
  25.         }
  26.         node->end = true;
  27.     }
  28.    
  29.     bool search(string word) {
  30.         TrieNode *node = root;
  31.         return search(word, 0, node);
  32.     }
  33.     bool search(string &word, int idx , TrieNode *node ) {
  34.         if(!node) return 0;
  35.         if(idx == word.size()) return node->end;
  36.         if(word[idx] != '.')
  37.             return search(word, idx+1, node->child[word[idx]-'a']);
  38.  
  39.         for(int key = 0; key< 26; key++)
  40.             if(search(word, idx+1, node->child[key]))
  41.                 return true;
  42.         return false;
  43.     }
  44. };
  45.  
  46. /**
  47.  * Your WordDictionary object will be instantiated and called as such:
  48.  * WordDictionary* obj = new WordDictionary();
  49.  * obj->addWord(word);
  50.  * bool param_2 = obj->search(word);
  51.  */
Advertisement
Add Comment
Please, Sign In to add comment