题目求只看字母(大写小写互通)的最长回文的长度,并输出长度和回文串
#include <iostream>
using namespace std;
const int MAX=22000005;
char c[MAX];
string s;
int cnt,p[MAX],maxright,mid,ans;
int Map[MAX],Mapcnt,starti;
void reads(){
char cs;
c[0]='.';
while((cs<'a'||cs>'z')&&(cs<'A'||cs>'Z')) cs = getchar();
while(cs!='\n'){
s = s+cs;
if ((cs>='a'&&cs<='z')||(cs>='A'&&cs<='Z')){
if (cs>='A'&&cs<='Z')cs=cs-'A'+'a';
c[++cnt]='#';
Map[cnt] = s.length()-1;
c[++cnt]=cs;
Map[cnt] = s.length()-1;
}
cs=getchar();
}
c[++cnt]='#';
}
void manacher(){
for (int i = 2; i <= cnt-1; i++){
if (i <= maxright) p[i] = min(p[(mid<<1)-i],maxright-i+1);
else p[i]=1;
while(c[i-p[i]]==c[i+p[i]])++p[i];
if (i+p[i]-1>maxright){maxright=i+p[i]-1;mid=i;}
if (p[i]>ans){
ans = p[i];
starti = i;
}
}
}
int main()
{
reads();
manacher();
printf("%d\n",ans-1);
for (int i = Map[starti-ans/2]; i <= Map[starti+ans/2]; i++) cout << s[i];
}
ans表示最长回文的长度
starti记录 答案这个字符串 的中间位置在只含有字母的c串中对应的下标
Map用来记录c映射到s的下标,应该是这个地方出了点问题QAQ
样例
Madam, I'm Adam
输出:
11
Madam, I'm Adam