题目来源
给一个字符串数组,求能组成回文串的两个元素的。
就是比较烦,但是倒不是很难。
代码如下:
class Solution {
public:
vector<vector<int>> palindromePairs(vector<string>& words) {
int len = words.size();
unordered_map<string, int> maps;
vector<vector<int>> res;
for (int i=0; i<len; i++) {
if (words[i] == "")
continue;
maps[words[i]] = i;
}
for (int i=0; i<len; i++) {
int wordLen = words[i].size();
if (wordLen == 0)
for (int j=0; j<len; j++) {
if (i != j && isPalindrome(words[j])) {
res.push_back(vector<int>{i, j});
res.push_back(vector<int>{j, i});
}
}
for (int j=wordLen; j>=1; j--) {
string left = words[i].substr(0, j);
string right = words[i].substr(j);
bool isleft = isPalindrome(left);
bool isright = isPalindrome(right);
reverse(left.begin(), left.end());
reverse(right.begin(), right.end());
if (isright && maps.count(left) != 0 && maps[left] != i) {
vector<int> pair{i, maps[left]};
res.push_back(pair);
}
if (isleft && maps.count(right) != 0 && maps[right] != i) {
vector<int> pair{maps[right], i};
res.push_back(pair);
}
}
}
return res;
}
bool isPalindrome(string &str)
{
if (str == "")
return true;
int p1 = 0, p2 = str.size() - 1;
while (p1 < p2) {
if (str[p1] != str[p2])
return false;
p1++;
p2--;
}
return true;
}
};