题意:给出一个有n个单词的字典,问有多少不同的两个单词的组合使得新组合成的单词是回文串。
思路:对于每个单词,从左到右遍历一遍,对于任意一个位置,如果它的左边是回文串且右边的逆序在字典中出现,那么就存在这么一种组合,同理,如果它的右边是回文串且左边的逆序在字典中出现,那么也存在这么一种组合。
class Solution {
public:
vector<vector<int>> palindromePairs(vector<string>& words) {
vector< vector<int> > ans;
unordered_map<string, int> dic;
int sz = words.size();
for (int i = 0; i < sz; i++)
dic[words[i]] = i;
for (int i = 0; i < sz; i++) {
int len = words[i].length();
dic.erase(words[i]);
for (int j = 0; j <= len; j++) {
string subL = words[i].substr(0, j);
string subR = words[i].substr(j);
string revL, revR;
revL = revL.assign(subL.rbegin(), subL.rend());
revR = revR.assign(subR.rbegin(), subR.rend());
if (j != len && isPalindrome(subR) && dic.count(revL))
ans.push_back(vector<int> {i, dic[revL]});
if (isPalindrome(subL) && dic.count(revR))
ans.push_back(vector<int> {dic[revR], i});
}
dic[words[i]] = i;
}
return ans;
}
bool isPalindrome(string s) {
int left = 0, right = s.length()-1;
while (left < right) {
if (s[left] != s[right])
return false;
left++;
right--;
}
return true;
}
};