336. Palindrome Pairs
https://leetcode.com/problems/palindrome-pairs/description/
Thoughts
Code
/*
* @lc app=leetcode id=336 lang=cpp
*
* [336] Palindrome Pairs
*/
// @lc code=start
class Solution {
public:
vector<vector<int>> palindromePairs(vector<string>& words) {
const int N = words.size();
unordered_map<string, int> dict;
for (int i = 0; i < N; ++i) {
auto rw = words[i];
reverse(rw.begin(), rw.end());
dict[rw] = i;
}
const auto palind = [](const string &s) {
for (int i = 0, j = s.length() - 1; i < j; ++i, --j) {
if (s[i] != s[j]) return false;
}
return true;
};
vector<vector<int>> res;
for (int i = 0; i < N; ++i) {
const auto w = words[i];
for (int j = 0; j <= w.length(); ++j) {
const auto l = w.substr(0, j), r = w.substr(j);
if (dict.count(l) && dict[l] != i && palind(r)) {
res.push_back({i, dict[l]});
}
if (dict.count(r) && dict[r] != i && palind(l) && !l.empty()) {
res.push_back({dict[r], i});
}
}
}
return res;
}
};
// @lc code=end
Analysis
Last updated