对给定的字符串,本题要求你输出最长对称子串的长度。例如,给定Is PAT&TAP symmetric?
,最长对称子串为s PAT&TAP s
,于是你应该输出11。
输入格式:
输入在一行中给出长度不超过1000的非空字符串。
输出格式:
在一行中输出最长对称子串的长度。
输入样例:
Is PAT&TAP symmetric?
输出样例:
11
分析:两种情况,一是对称中心为一个字符,如12321;另一个是对称中心为两个字符,如123321。接下来暴力就好了
代码:
#include<cstring>
#include<iostream>
#include<cstdio>
using namespace std;
char str[2000];
int cnt = 0;
void solve(char str[])
{
int len = strlen(str);
int m = 0;
for(int i = 1; i < len;i++)///对称中心为1个字符
{
m = 1;
if(str[i-1]==str[i])
{
int j = i;
while(str[j-m-1]==str[j+m]&&j-m-1>=0&&j+m<len)m++;
if(m*2>cnt)cnt=m*2;
}
}
m = 0;
for(int i = 0; i< len; i++)///对称中心为两个字符
{
m = 1;
int j = i;
while(str[j-m]==str[j+m]&&j-m>=0&&j+m<len)m++;
if(m*2-1>cnt)cnt=m*2-1;
}
cout<<cnt<<endl;
}
int main()
{
scanf("%[^\n]",str);///字符串输入
solve(str);
return 0;
}