knakul853

Untitled

Jun 12th, 2020
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.10 KB | None | 0 0
  1. /**
  2. knakul853
  3. **/
  4. class Trie {
  5.    
  6.     public:
  7.     Trie* children[26];
  8.     bool leaf;
  9.    
  10.     Trie()
  11.     {
  12.            leaf = false;
  13.          for(int i=0;i<26;i++)
  14.              children[i] = NULL;
  15.     }
  16. };
  17.  
  18. class MagicDictionary {
  19.    
  20. private:
  21.     Trie* root = new Trie();
  22. public:
  23.     /** Initialize your data structure here. */
  24.     MagicDictionary() {
  25.        
  26.     }
  27.    
  28.     void insert(string word)
  29.     {
  30.          Trie* node = root;
  31.        
  32.         int n = (int)word.size();
  33.         for( int i=0;i < n; i++ )
  34.         {
  35.             char ch = word[i];
  36.            
  37.             if(!node->children[ch - 'a'])
  38.                 node->children[ch-'a'] = new Trie();
  39.             node = node->children[ch-'a'];
  40.         }
  41.        
  42.         node->leaf = true;
  43.     }
  44.     /** Build a dictionary through a list of words */
  45.     void buildDict(vector<string> dict) {
  46.        
  47.         int n = (int)dict.size();
  48.        
  49.         for( int i=0;i<n;i++ )
  50.         {
  51.             insert(dict[i]);
  52.         }
  53.     }
  54.    
  55.     bool found(string word)
  56.     {
  57.          Trie* node = root;
  58.        
  59.         for( char c: word )
  60.         {
  61.             if( !node->children[c-'a']) return false;
  62.            
  63.             node = node->children[c - 'a'];
  64.         }
  65.        
  66.         return node->leaf;
  67.     }
  68.    
  69.     /** Returns if there is any word in the trie that equals to the given word after modifying exactly                        one character */
  70.     bool search(string word) {
  71.        
  72.         for(int i=0;i<(int)word.size(); i++)
  73.         {
  74.             char temp = word[i];
  75.            
  76.             for(char ch='a'; ch <='z'; ch++ )
  77.             {
  78.                 word[i] = ch;
  79.                 if(ch == temp)continue;
  80.                
  81.                 if( found(word)) return true;
  82.                
  83.             }
  84.            
  85.             word[i] = temp;
  86.         }
  87.         return false;
  88.        
  89.        
  90.     }
  91. };
  92.  
  93. /**
  94.  * Your MagicDictionary object will be instantiated and called as such:
  95.  * MagicDictionary* obj = new MagicDictionary();
  96.  * obj->buildDict(dict);
  97.  * bool param_2 = obj->search(word);
  98.  */
Add Comment
Please, Sign In to add comment