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.
开始竟然看成最大的逆序子串了
回文数有两种情况
(例)
1.abba
2.abgba
char* longestPalindrome(char* s) {
int i=0,k,count,countmax[2],flag=0,start,end;
if(s[i]=='\0'){
return NULL;
}
if(s[i+1]=='\0'){
return s;
}
count=countmax[0]=0;
while(s[i+1]!='\0'){
if(s[i]==s[i+1]){
k=0;
count=0;
while(i-k>=0&&s[i+1+k]!='\0'&&s[i-k]==s[i+1+k]){
k++;
count+=2;
}
}
if(count>countmax[0]){
countmax[0]=count;
countmax[1]=i;
}
i++;
}
for(i=0;s[i+2]!='\0';i++){
if(s[i]==s[i+2]){
k=0;
count=1;
while(i-k>=0&&s[i+2+k]!='\0'&&s[i-k]==s[i+2+k]){
k++;
count+=2;
}
}
if(count>countmax[0]){
countmax[0]=count;
countmax[1]=i+1;
flag=1;
}
}
start=end=countmax[1];
for(i=0;i<countmax[0]/2;i++){
if(flag==0){
end++;
flag=1;
}
else{
start--;
end++;
}
}
for(i=0;start+i<=end;i++){
s[i]=s[start+i];
}
s[i]='\0';
return s;
}