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.
思路:所遍历字符为一个回文子串的中间字符,则可以得出以该字符为中间字符的最长回文子串的长度,便可得最长回文子串
例子:s"abccba"
i=1,以s[1]:b为中间字符的最长回文子串长度为1
i=2,以s[2]:c为中间字符的最长回文子串长度为1
……
class Solution {
public:
string longestPalindrome(string s) {
string longestPal;
int start=0;
int end=0;
int maxlen=1;
for(int i=1; i<s.length(); ++i)
{
int len=0;
if(s[i] == s[i-1])
{
len+=2;
int j=1;
while(i+j<s.length() && i-1-j>=0 && s[i+j]==s[i-1-j])
{
len+=2;
++j;
}
if(len>maxlen)
{
start=i-j;
end=i+j-1;
maxlen=len;
}
}
len=0;
if(s[i+1] == s[i-1])
{
++len;
int j=1;
while(i+j<s.length() && i-j>=0 && s[i+j]==s[i-j])
{
len+=2;
++j;
}
if(len>maxlen)
{
start=i-j+1;
end=i+j-1;
maxlen=len;
}
}
}
for(int i=start; i<=end; ++i)
{
longestPal.push_back(s[i]);
}
return longestPal;
}
};