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"]
参考资料:here。
因为参考资料已经讲解得非常好了,我们这里就不在做说明了。不过需要注意得是,原解答没有用到set这个数据结构,所以他专门使用一个for循环来解决边界情况。
class Solution {
private:
bool isPanlindrome(string s) {
int left = 0, right = int(s.size() - 1);
while (left < right) {
if (s[left] != s[right]) return false;
left++; right--;
}
return true;
}
public:
vector<vector<int>> palindromePairs(vector<string>& words) {
map<string, int> m;
for (int i = 0; i < words.size();i++) {
string word = words[i];
reverse(word.begin(), word.end());
m[word] = i;
}
set<vector<int>> s;
for (int i = 0; i < words.size(); i++) {
string word = words[i];
for (int j = 0; j <= word.size(); j++) {
string left = word.substr(0, j);
string right = word.substr(j);
if (m.find(left) != m.end()) {
if (isPanlindrome(right) && m[left] != i) {
s.insert({i, m[left]});
}
}
if (m.find(right) != m.end()) {
if (isPanlindrome(left) && m[right] != i) {
s.insert({ m[right], i });
}
}
}
}
vector<vector<int>> ans(s.begin(), s.end());
return ans;
}
};