|
| 1 | +class TrieNode { |
| 2 | + public: |
| 3 | + char data; |
| 4 | + TrieNode* children[26]; |
| 5 | + bool isTerminal; |
| 6 | + |
| 7 | + TrieNode(char data){ |
| 8 | + this -> data = data; |
| 9 | + for(int i = 0; i < 26; i++) children[i] = NULL; |
| 10 | + isTerminal = false; |
| 11 | + } |
| 12 | +}; |
| 13 | + |
| 14 | +class Trie { |
| 15 | + public: |
| 16 | + TrieNode* root; |
| 17 | + |
| 18 | + Trie(char ch) { |
| 19 | + root = new TrieNode(ch); |
| 20 | + } |
| 21 | + |
| 22 | + void insertUtil(TrieNode* root, string word, int index){ |
| 23 | + if(index == word.size()){ |
| 24 | + root -> isTerminal = true; |
| 25 | + return; |
| 26 | + } |
| 27 | + |
| 28 | + int charIndex = word[index] - 'a'; |
| 29 | + if(root -> children[charIndex] == NULL) root -> children[charIndex] = new TrieNode(word[index]); |
| 30 | + |
| 31 | + insertUtil(root -> children[charIndex], word, index+1); |
| 32 | + } |
| 33 | + |
| 34 | + void insertWord(string word){ |
| 35 | + insertUtil(root, word, 0); |
| 36 | + } |
| 37 | + |
| 38 | + |
| 39 | + |
| 40 | + void printSuggestions(TrieNode* curr, vector<string>& temp, string prefix){ |
| 41 | + if(curr -> isTerminal){ |
| 42 | + temp.push_back(prefix); |
| 43 | + } |
| 44 | + |
| 45 | + for(char ch = 'a'; ch <= 'z'; ch++){ |
| 46 | + TrieNode* next = curr -> children[ch - 'a']; |
| 47 | + if(next != NULL){ |
| 48 | + prefix.push_back(ch); |
| 49 | + printSuggestions(next, temp, prefix); |
| 50 | + prefix.pop_back(); |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + vector<vector<string>> getSuggestions(string str){ |
| 56 | + TrieNode* prev = root; |
| 57 | + vector<vector<string>> output; |
| 58 | + |
| 59 | + string prefix = ""; |
| 60 | + |
| 61 | + for(int i = 0; i < str.length(); i++){ |
| 62 | + char lastChar = str[i]; |
| 63 | + prefix.push_back(lastChar); |
| 64 | + |
| 65 | + TrieNode* curr = prev -> children[lastChar - 'a']; |
| 66 | + if(curr == NULL) { |
| 67 | + for(int j = i; j < str.length(); j++) output.push_back({"0"}); |
| 68 | + break; |
| 69 | + } |
| 70 | + |
| 71 | + vector<string> temp; |
| 72 | + printSuggestions(curr, temp, prefix); |
| 73 | + |
| 74 | + if(temp.empty()) output.push_back({"0"}); |
| 75 | + else{ |
| 76 | + sort(temp.begin(), temp.end()); |
| 77 | + output.push_back(temp); |
| 78 | + } |
| 79 | + |
| 80 | + prev = curr; |
| 81 | + } |
| 82 | + |
| 83 | + return output; |
| 84 | + } |
| 85 | + |
| 86 | +}; |
| 87 | + |
| 88 | +class Solution { |
| 89 | +public: |
| 90 | + vector<vector<string>> displayContacts(int n, string contact[], string s) { |
| 91 | + Trie* t = new Trie('\0'); |
| 92 | + |
| 93 | + for(int i = 0; i < n; i++){ |
| 94 | + string str = contact[i]; |
| 95 | + t -> insertWord(str); |
| 96 | + } |
| 97 | + |
| 98 | + return t -> getSuggestions(s); |
| 99 | + } |
| 100 | +}; |
0 commit comments