题目:
对给定的字符串,本题要求你输出最长对称子串的长度。例如,给定Is PAT&TAP symmetric?,最长对称子串为s PAT&TAP s,于是你应该输出11。
输入格式:
输入在一行中给出长度不超过1000的非空字符串。
输出格式:
在一行中输出最长对称子串的长度。
输入样例:
Is PAT&TAP symmetric?
输出样例:
11
我的答案
#include<stdio.h>
#include<string.h>
int main(){
char sa[1100];
char sb[1100];
gets(sa);
//Is PAT&TAP symmetric? sa
//?cirtemmys PAT&TAP sI sb
int len=strlen(sa);
int count=0,max=0,k=0;
for(int j=len-1;j>=0;j--){
sb[j]=sa[k++];
}
for(int i=0;i<len;i++){
for(int j=0;j<len;j++){
if(sa[i]==sb[j]){
int h=i,l=j;
while(sa[h++]==sb[l++]){
count++;
}
if(max<count) max=count;
count=0;
}
else count=0;
}
}
printf("%d\n",max);
// puts(sb);
return 0;
}
#endif
/*
int main(){
char str[1100];
int a[1100]={0};
gets(str);
int len=strlen(str);
for(int i=0;i<len;i++){
int s=i;//设两个指针s,k
int k=i+2;
for(int j=0;j<len;j++){
if(str[s]==str[k]){
a[i+1]+=2;
s--;
if(s<0){
break;
}
k++;
}else{
break;
}
}
}
int max=0;
for(int i=0;i<len;i++){
if(a[i]>max){
max=a[i];
}
}
printf("%d\n",max+1);
return 0;
}
正确答案
#include<bits/stdc++.h>
using namespace std;
int main(){
int ans=0;
int len;
string line;
getline(cin,line);
len=line.length();
//Is PAT&TAP symmetric?
//?cirtemmys PAT&TAP sI
for( int i=0; i<len; i++ ){
for( int j=len; j>=i&&j-i+1>ans; j--){
if(line[i]==line[j]){
string buf1=line.substr(i,j-i+1);//截取字符串
string buf2=buf1;
reverse(buf2.begin(),buf2.end());//倒置字符串
if(buf2==buf1) ans=max(ans,(int)buf2.length());
}
}
}
printf("%d\n",ans);
return 0;
}