您的位置:首页 > 其它

Leetcode 336 回文对

2016-09-13 17:58 211 查看
本文借鉴了https://discuss.leetcode.com/topic/51771/clean-c-implementation

原题回放

给定一个无重复字符串列表words,找出所有的序偶对(i,j),如果words[i]+words[j]是一个回文串的话。

例如:

words = [“bat”, “tab”, “cat”]

返回 [[0,1], [1,0]]

回文串即[“battab”, “tabbat”]

代码

class Solution{
public:
bool isPalindrome(string& s, int start, int end){
while(start < end)
if(s[start++] != s[end--])
return false;
}

vector<vector<int>> palindromePairs(vector<string> words){
vector<vector<int>> ans;
unordered_map<string, int> dict;
int len = words.size();
for(int i=0; i<len; i++)
dict[words[i]] = i;
for(int i=0; i<len; i++){
string cur = words[i];
int clen = cur.size();
for(int j=0; j<=clen; j++){
// 找后缀
if(isPalindrome(cur, j, clen-1)){
// 后缀可以为空
string suffix = cur.substr(0, j);
reverse(suffix.begin(), suffix.end());
if(dict.find(suffix)!=dict.end() && i!=dict[suffix])
ans.push_back({i, dict[suffix]});
}
// 找前缀
if(j>0 && isPalindrome(cur, 0, j-1)){
string prefix = cur.substr(j);
reverse(prefix.begin(), prefix.end());
if(dict.find[prefix]!=dict.end() && i!=dict[prefix])
ans.push_back({dict[prefix], i});
}
}
}
return ans;
}
};


单纯记录一下,方便以后复习。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 回文对