L2-008. 最长对称子串
时间限制
100 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
陈越
对给定的字符串,本题要求你输出最长对称子串的长度。例如,给定"Is PAT&TAP symmetric?",最长对称子串为"s PAT&TAP s",于是你应该输出11。
输入格式:
输入在一行中给出长度不超过1000的非空字符串。
输出格式:
在一行中输出最长对称子串的长度。
输入样例:Is PAT&TAP symmetric?输出样例:
11
思路:因为长度较短,直接暴力。i位置开始,从最后往前逐个比较比较。
#include<cstdio>
#include<cstring>
using namespace std;
int main(){
char s[1005];
gets(s);
int len = strlen(s),max = 1;
for(int i = 0; i < len; i++){
int count = 1,k = i;
for(int j = len-1; j > i; j--){
if(s[k] == s[j]){
if(k + 1 == j){
max = (max >= count*2) ? max : count*2;
break;
}
if(k == j){
max = (max >= count*2-1) ? max : count*2-1;
break;
}
if(s[k+1] == s[j-1]){
count++;
k++;
}else count = 1;
}
}
}
printf("%d", max);
return 0;
}