7-12 最长对称子串 (25分)
对给定的字符串,本题要求你输出最长对称子串的长度。例如,给定Is PAT&TAP symmetric?
,最长对称子串为s PAT&TAP s
,于是你应该输出11
。
输入格式:
输入在一行中给出长度不超过1000的非空字符串。
输出格式:
在一行中输出最长对称子串的长度。
输入样例:
Is PAT&TAP symmetric?
输出样例:
11
思路:
把给定的字符串逆序,暴力循环每一个每一个字符,在逆序字符串种查找第一个与之相同的字符,然后从该位置往后依次判断是否相等,记录长度。
#include <iostream>
#include<bits/stdc++.h>
#define ll long long
const int N = 1e4 +10;
//const int M = 1e6 +10;
using namespace std;
int main()
{
int maxn=-1;
string s;
getline(cin,s); //输入给定的字符串
char str[1111];
int len=s.length();
int i;
int j=0;
for(i=len-1; i>=0; i--) //获得逆序字符串
{
str[j++]=s[i];
}
str[len]='\0';
//printf("%s\n",str);
for(i=0; i<len; i++)
{
int cnt=1;
int x,y;
for(j=0; j<len; j++)
{
if(s[i]==str[j]) //找到开始判断的位置
{
x=i;
y=j;
break;
}
}
//printf("%c\n",s[i]);
while(s[++x]==str[++y]&&x<len&&y<len)
{
cnt++;
}
maxn=max(maxn,cnt);
}
printf("%d\n",maxn);
return 0;
}