|
| 1 | +class TrieNode{ |
| 2 | + public: |
| 3 | + bool isEnd; |
| 4 | + vector<TrieNode*> dict; |
| 5 | + TrieNode(){ |
| 6 | + isEnd = false; |
| 7 | + dict.resize(26,nullptr); |
| 8 | + } |
| 9 | +}; |
| 10 | +class WordDictionary { |
| 11 | +public: |
| 12 | + /** Initialize your data structure here. */ |
| 13 | + TrieNode* root; |
| 14 | + WordDictionary() { |
| 15 | + root = new TrieNode(); |
| 16 | + } |
| 17 | + |
| 18 | + /** Adds a word into the data structure. */ |
| 19 | + // Addition of word in the trie is fairly simple. |
| 20 | + // If you are not able to understand it, then solve the below question first : |
| 21 | + // https://leetcode.com/problems/implement-trie-prefix-tree/ |
| 22 | + void addWord(string word) { |
| 23 | + TrieNode* itr = root; |
| 24 | + for(int i=0;i<word.length();i++){ |
| 25 | + if(itr->dict[word[i]-'a']==nullptr){ |
| 26 | + itr->dict[word[i]-'a'] = new TrieNode(); |
| 27 | + } |
| 28 | + itr = itr->dict[word[i]-'a']; |
| 29 | + } |
| 30 | + itr->isEnd = true; |
| 31 | + } |
| 32 | + |
| 33 | + |
| 34 | + // Recursive function for searching the string in the trie. |
| 35 | + bool func(TrieNode* root, string word, int pos){ |
| 36 | + // When pos becomes equal to length of the word i.e. we are at the end of the string. |
| 37 | + if(word.length()==pos){ |
| 38 | + // If the string is present in the trie then "root" will be at the end of the trie. |
| 39 | + if(root->isEnd) |
| 40 | + return true; |
| 41 | + return false; |
| 42 | + } |
| 43 | + // If the character is not '.' then it is fairly simple. |
| 44 | + // We just need to check whether the word[pos] is present in the trie or not. |
| 45 | + if(word[pos]!='.'){ |
| 46 | + if(root->dict[word[pos]-'a']!=nullptr) |
| 47 | + return func(root->dict[word[pos]-'a'], word,pos+1); |
| 48 | + else |
| 49 | + return false; |
| 50 | + } |
| 51 | + else{ |
| 52 | + // Now, if we encounter '.' then we need to check every possible alphabet i.e. from a-z |
| 53 | + // If we find any alphabet which is present in the trie, |
| 54 | + // then we have to make the recursive call to the function with now --> pos + 1. |
| 55 | + // If we encounter null node then we will continue and check the rest of the alphabets. |
| 56 | + for(int i=0;i<26;i++){ |
| 57 | + if(root->dict[i]==nullptr) |
| 58 | + continue; |
| 59 | + else{ |
| 60 | + if(func(root->dict[i],word,pos+1)) |
| 61 | + return true; |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + // If after checking everything, we don't find the alphabet in the trie -> |
| 66 | + return false; |
| 67 | + } |
| 68 | + bool search(string word) { |
| 69 | + return func(root, word, 0); |
| 70 | + } |
| 71 | +}; |
0 commit comments