这题考察最基本的回文串处理,采取的算法是枚举回文串的中心点,不过要分回文串长度是奇数和偶数的情况。
/*
ID: ljracm1
LANG: C++
PROB: calfflac
*/
#include<cstdio>
#include<cstring>
#include<ctype.h>
#define T
using namespace std;
int main(){
#ifdef T
freopen("calfflac.in","r",stdin);
freopen("calfflac.out","w",stdout);
#endif
char ch;
char str1[20005],str[20005];
int len1=0,len=0,h[20005]; //h[20005]专门用来记录原字符串中非标点字符的实际位置
while(scanf("%c",&ch)!=EOF){
if((ch>='A'&&ch<='Z')||(ch>='a'&&ch<='z')){
h[len1]=len;
str[len++]=ch;
str1[len1++]=tolower(ch);
str[len]='\0';
str1[len]='\0';
}
else{
str[len++]=ch;
str[len]='\0';
}
}
int maxn1 = 0, center1 =0;//maxn1记录最长回文串为奇数的情况, center1为中心节点的起点
for(int i=0; i<len1; i++){//枚举中心节点的情况
int l=0;//从起始长度为0算起
while(str1[l+i]==str1[i-l]&&l+i<len1&&i-l>=0)l++;
if(maxn1<l){
maxn1 = l;
center1 = i;
}
}
int maxn2 = 0, center2 = 0;
for(int i=0; i<len1; i++){
int l=0;
while(str1[l+1+i]==str1[i-l]&&l+i<len1&&i-l>=0)l++;
if(maxn2<l){
maxn2 = l;
center2 = i;
}
}
//前面maxn1与maxn2均是一半长的情况,将它变回实际长度进行比较
maxn1 = maxn1*2-1;
maxn2 *= 2;
int maxn,center;
if(maxn1>maxn2){
maxn = maxn1; center = center1;
}
else{
maxn = maxn2; center = center2;
}
printf("%d\n",maxn);
for(int i=h[center-(maxn+1)/2+1]; i<=h[center-(maxn+1)/2+maxn]; i++)
printf("%c",str[i]);
printf("\n");
return 0;
}