336. Palindrome Pairs
Given a list of unique words, find all pairs of distinct indices (i, j) in the given list, so that the concatenation of the two words, i.e. words[i] + words[j] is a palindrome.
Example 1:
Input: ["abcd","dcba","lls","s","sssll"]
Output: [[0,1],[1,0],[3,2],[2,4]]
Explanation: The palindromes are ["dcbaabcd","abcddcba","slls","llssssll"]Example 2:
Input: ["bat","tab","cat"]
Output: [[0,1],[1,0]]
Explanation: The palindromes are ["battab","tabbat"]// Hashmap + Treeset
bool isValid(const string& s, int i, int j) {
while (i < j) {
if (s[i++] != s[j--]) return false;
}
return true;
}
vector<vector<int>> palindromePairs(vector<string>& words) {
vector<vector<int> > res;
unordered_map<string, size_t> str2idx;
set<size_t> strLen;
for (size_t i = 0; i < words.size(); ++i) {
str2idx[words[i]] = i;
strLen.insert(words[i].length());
}
for (size_t i = 0; i < words.size(); ++i) {
string tmp = words[i];
size_t len = tmp.length();
reverse(tmp.begin(), tmp.end());
if (str2idx.count(tmp) && str2idx[tmp] != i) { // avoid some palindromic words
res.push_back({i, str2idx[tmp]});
}
const auto len_it = strLen.find(len);
if (len_it == strLen.end()) continue;
for (auto it = strLen.begin(); it != len_it; ++it) {
int d = *it;
// Two cases
// (1) cur + tmp[d...len - 1]
if (isValid(tmp, 0, len - 1 - d) && str2idx.count(tmp.substr(len - d))) {
res.push_back({i, str2idx[tmp.substr(len - d)]});
}
// (1) tmp[0...d - 1] + cur
if (isValid(tmp, d, len - 1) && str2idx.count(tmp.substr(0, d))) {
res.push_back({str2idx[tmp.substr(0, d)], i});
}
}
}
return res;
}Last updated
Was this helpful?