|
| 1 | +class TrieNode{ |
| 2 | + public: |
| 3 | + char data; |
| 4 | + TrieNode* children[26]; |
| 5 | + int childCount; |
| 6 | + bool isTerminal; |
| 7 | + |
| 8 | + TrieNode(int data){ |
| 9 | + this -> data = data; |
| 10 | + for(int i = 0; i < 26; i++) children[i] = NULL; |
| 11 | + isTerminal = false; |
| 12 | + childCount = 0; |
| 13 | + } |
| 14 | +}; |
| 15 | + |
| 16 | +class Trie{ |
| 17 | + public: |
| 18 | + TrieNode* root; |
| 19 | + Trie(char ch){ |
| 20 | + root = new TrieNode(ch); |
| 21 | + } |
| 22 | + |
| 23 | + void insertUtil(TrieNode* root, string& word, int index){ |
| 24 | + if(index == word.size()){ |
| 25 | + root -> isTerminal = true; |
| 26 | + return; |
| 27 | + } |
| 28 | + |
| 29 | + int charIndex = word[index] - 'a'; |
| 30 | + if(root -> children[charIndex] == NULL){ |
| 31 | + root -> children[charIndex] = new TrieNode(word[index]); |
| 32 | + root -> childCount++; |
| 33 | + } |
| 34 | + |
| 35 | + insertUtil(root -> children[charIndex], word, index+1); |
| 36 | + } |
| 37 | + |
| 38 | + void insertWord(string& word){ |
| 39 | + insertUtil(root, word, 0); |
| 40 | + } |
| 41 | + |
| 42 | + void lcp(string str, string& ans){ |
| 43 | + TrieNode* node = root; |
| 44 | + for(int i = 0; i < str.length(); i++){ |
| 45 | + char ch = str[i]; |
| 46 | + |
| 47 | + if(node -> childCount == 1) { |
| 48 | + ans.push_back(ch); |
| 49 | + |
| 50 | + int index = ch - 'a'; |
| 51 | + |
| 52 | + node = node -> children[index]; |
| 53 | + }else break; |
| 54 | + |
| 55 | + if(node -> isTerminal) break; |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + ~Trie() { |
| 60 | + deleteTrie(root); |
| 61 | + } |
| 62 | + private: |
| 63 | + void deleteTrie(TrieNode* node) { |
| 64 | + if (!node) return; |
| 65 | + for (int i = 0; i < 26; i++) { |
| 66 | + deleteTrie(node->children[i]); |
| 67 | + } |
| 68 | + delete node; |
| 69 | + } |
| 70 | +}; |
| 71 | +class Solution { |
| 72 | +public: |
| 73 | + string longestCommonPrefix(vector<string>& strs) { |
| 74 | + if(strs.empty()) return ""; |
| 75 | + |
| 76 | + for(string& str : strs) if(str.empty()) return ""; |
| 77 | + |
| 78 | + Trie* t = new Trie('\0'); |
| 79 | + |
| 80 | + for(int i = 0; i < strs.size(); i++) t->insertWord(strs[i]); |
| 81 | + |
| 82 | + string first = strs[0]; |
| 83 | + string ans = ""; |
| 84 | + |
| 85 | + t -> lcp(first, ans); |
| 86 | + |
| 87 | + return ans; |
| 88 | + } |
| 89 | +}; |
0 commit comments