对给定的字符串,本题要求你输出最长对称子串的长度。例如,给定Is PAT&TAP symmetric?
,最长对称子串为s PAT&TAP s
,于是你应该输出11。
输入格式:
输入在一行中给出长度不超过1000的非空字符串。
输出格式:
在一行中输出最长对称子串的长度。
输入样例:
Is PAT&TAP symmetric?
输出样例:
11
题意
如上
题解
模拟,直接暴力莽,代码有解释
代码
1 #include<stdio.h> 2 using namespace std; 3 4 char a[1005]; 5 6 int hw(int left,int right){ 7 int mid=(left+right)/2; 8 int ans=0,k=0,f=1; 9 if( (left+right)%2==0 )k=1; 10 while(left<right){ 11 if(a[left++]!=a[right--]){ 12 f=0;//不是回文串 13 break; 14 } 15 ans++; 16 } 17 if(f){ 18 if(k==1) 19 return 2*ans+1;//偶数2*对称的个数+中间的1个 20 else 21 return 2*ans;//奇数2*对称的个数 22 } 23 else 24 return 0; 25 } 26 27 int main(){ 28 int max=0; 29 gets(a); 30 for(int i=0;i<a[i];i++){ 31 for(int j=i;j<a[j];j++){ 32 int len=hw(i,j); 33 if(len>max) 34 max=len; 35 } 36 } 37 printf("%d ",max); 38 return 0; 39 }