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.
class Solution {
public:
string longestPalindrome(string s) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(s.empty() )
return "";
int imax = 0;
int ileft=0, iright=0;
for(int i=0; i<s.size(); ++i)
{
if(i-1>=0 )
{
if(s[i] == s[i-1])//even
{
int ltmp=i-2, rtmp=i+1;
while(ltmp>=0 && rtmp<s.size() )
{
if(s[ltmp] != s[rtmp])
break;
--ltmp;
++rtmp;
}
if(imax < rtmp-ltmp-1)
{
imax = rtmp-ltmp-1;
ileft = ltmp+1;
iright = rtmp-1;
}
}
//odd
int ltmp=i-1,rtmp=i+1;
while(ltmp>=0 && rtmp<s.size() )
{
if(s[ltmp] != s[rtmp])
break;
--ltmp;
++rtmp;
}
if(imax < rtmp-ltmp-1)
{
imax = rtmp-ltmp-1;
ileft = ltmp+1;
iright = rtmp-1;
}
}
}
return s.substr(ileft,iright+1-ileft);
}
};