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.
string longestPalindrome(string s) {
int m=0,n=0;
int len=s.size();
int length=len*2+1;
int *p=new int[length];
string str(length,'#');
int max=0,idx=1;//idx应该是已经找出的最靠右的回文子串的中间位置
//int hashtable[256];
//char ch=' ';
//memset(hashtable,-1,sizeof(hashtable));
memset(p,0,length*sizeof(int ));
//str[]
str[1]=s[0];
for (int i = 1; i < len; i++)
{
str[2*i+1]=s[i];
}
//for (int i = 0; i < len; i++)
//{
// ch=s.at(i);
// hashtable[ch]=0;
//}
for (int i = 1; i < length-1; i++)
{
if(max>i){
p[i]=p[((idx<<1)-i)]<(m-i)?p[(idx<<1)-i]:(m-1);
}
while ((i-p[i]-1)>-1&&(p[i]+i+1)<length&&str[p[i]+i+1]==str[i-p[i]-1])
{
p[i]++;
}
if((i+p[i])>max){
idx=i;
max=i+p[i];
}
}
int radius=0;
int center=0;
print(p,length);
for (int i = 0; i < length; i++)
{
if(p[i]>radius){
radius=p[i];
center=i;
}
}
cout<<endl;
return s.substr(center/2-radius/2,radius);
}
简便的解法:
string longestPalindrome01(string s){
int loc=0,length=0;
int j=0;
for (int i = 0; i < s.size(); i++)
{
j=0;
while ((i-j)>0&&(i+j<s.size())&&s[i-j]==s[i+j])
{
if(j*2+1>length){
length=j*2+1;
loc=i-j;
}
j++;
}
j=0;
while(i-j>=0 && i+j+1<s.size() && s[i-j]==s[i+j+1]){
if(j*2+2>length){
length=j*2+2;
loc=i-j;
}
j++;
}
}
return s.substr(loc,length);
}