|
| 1 | +/* |
| 2 | +Palindrome Pairs |
| 3 | +================ |
| 4 | +
|
| 5 | +Given a list of unique words, return all the pairs of the distinct indices (i, j) in the given list, so that the concatenation of the two words words[i] + words[j] is a palindrome. |
| 6 | +
|
| 7 | +Example 1: |
| 8 | +Input: words = ["abcd","dcba","lls","s","sssll"] |
| 9 | +Output: [[0,1],[1,0],[3,2],[2,4]] |
| 10 | +Explanation: The palindromes are ["dcbaabcd","abcddcba","slls","llssssll"] |
| 11 | +
|
| 12 | +Example 2: |
| 13 | +Input: words = ["bat","tab","cat"] |
| 14 | +Output: [[0,1],[1,0]] |
| 15 | +Explanation: The palindromes are ["battab","tabbat"] |
| 16 | +
|
| 17 | +Example 3: |
| 18 | +Input: words = ["a",""] |
| 19 | +Output: [[0,1],[1,0]] |
| 20 | +
|
| 21 | +Constraints: |
| 22 | +1 <= words.length <= 5000 |
| 23 | +0 <= words[i].length <= 300 |
| 24 | +words[i] consists of lower-case English letters. |
| 25 | +*/ |
| 26 | + |
| 27 | +class Solution |
| 28 | +{ |
| 29 | +public: |
| 30 | + bool palendrome(string str) |
| 31 | + { |
| 32 | + int i = 0, j = str.size() - 1; |
| 33 | + while (i < j) |
| 34 | + { |
| 35 | + if (str[i++] != str[j--]) |
| 36 | + return false; |
| 37 | + } |
| 38 | + return true; |
| 39 | + } |
| 40 | + |
| 41 | + vector<vector<int>> palindromePairs(vector<string> &arr) |
| 42 | + { |
| 43 | + unordered_map<string, int> words; |
| 44 | + vector<vector<int>> ans; |
| 45 | + vector<bool> isPal(arr.size(), 0); |
| 46 | + |
| 47 | + for (int i = 0; i < arr.size(); ++i) |
| 48 | + isPal[i] = palendrome(arr[i]); |
| 49 | + |
| 50 | + for (int i = 0; i < arr.size(); ++i) |
| 51 | + words[arr[i]] = i; |
| 52 | + |
| 53 | + for (int i = 0; i < arr.size(); ++i) |
| 54 | + { |
| 55 | + // first type, right me add krke palendrome bnao |
| 56 | + // ie, we have to find prefix ka reverse |
| 57 | + string curr = ""; |
| 58 | + for (int j = 0; j < arr[i].size(); ++j) |
| 59 | + { |
| 60 | + curr = arr[i][j] + curr; |
| 61 | + if (words.count(curr) && words[curr] != i && palendrome(arr[i] + curr)) |
| 62 | + { |
| 63 | + ans.push_back({i, words[curr]}); |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + // phir suffix ka reverse dekhna hai |
| 68 | + curr = ""; |
| 69 | + for (int j = arr[i].size() - 1; j > 0; --j) |
| 70 | + { |
| 71 | + curr += arr[i][j]; |
| 72 | + if (words.count(curr) && words[curr] != i && palendrome(curr + arr[i])) |
| 73 | + { |
| 74 | + ans.push_back({words[curr], i}); |
| 75 | + } |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + // match empty string with all palendromes |
| 80 | + for (int i = 0; i < arr.size(); ++i) |
| 81 | + { |
| 82 | + if (arr[i] == "") |
| 83 | + { |
| 84 | + for (int j = 0; j < arr.size(); ++j) |
| 85 | + { |
| 86 | + if (i != j && isPal[j]) |
| 87 | + { |
| 88 | + ans.push_back({i, j}); |
| 89 | + ans.push_back({j, i}); |
| 90 | + } |
| 91 | + } |
| 92 | + } |
| 93 | + } |
| 94 | + |
| 95 | + return ans; |
| 96 | + } |
| 97 | +}; |
0 commit comments