Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
玩了两天dota2,罪过罪过,还是应该老老实实刷题啊。
题目求得是最长的回文子串,这里使用的是暴力的解法,也就是解决两种回文"asdsa"以及"assa",即奇数以及偶数回文,相当于用了二重循环,代码如下:
class Solution {
public:
string longestPalindrome(string s) {
if (!s.size()) return "";
string ret;
string tmp;
for (int i = ; i < s.size(); ++i){
tmp = findPal(s, i - , i + );
if (tmp.size() > ret.size())
ret = tmp;
tmp = findPal(s, i , i + );
if (tmp.size() > ret.size())
ret = tmp;
}
return ret;
} string findPal(string & s, int left, int right)
{
if (left < )
return s.substr(left + , );
if (right >= s.size())
return s.substr(right - , ); while (left >= && right < s.size()){
if (s[left] != s[right])
break;
left--;
right++;
}
left++;
return s.substr(left, right - left);
}
};