题目描述:
Given a string, you are supposed to output the length of the longest symmetric sub-string. For example, given “Is PAT&TAP symmetric?”, the longest symmetric sub-string is “s PAT&TAP s”, hence you must output 11.
翻译:给你一个字符串你需要输出最长的对称字串长度。例如,给你”Is PAT&TAP symmetric?”, 最长的对称子串是 “s PAT&TAP s”, 所以你需要输出11。
INPUT FORMAT
Each input file contains one test case which gives a non-empty string of length no more than 1000.
翻译:每个输入文件包含一组测试数据,每组测试数据包含一个长度不超过1000的非空字符串。
OUTPUT FORMAT
For each test case, simply print the maximum length in a line.
翻译:对于每组输入数据,输出一行最长的长度。
Sample Input:
Is PAT&TAP symmetric?
Sample Output:
11
解题思路
遍历每个字符,比较左边的和右边的字符是否一致,如果不一致或越界则退出。注意还要比较两个字符的情况。复杂度最高为O(2*1000^2),还是
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<string>
#include<algorithm>
#define INF 99999999
using namespace std;
int main(){
string s;
getline(cin,s);
int Max=0;
int length=s.size();
for(int i=0;i<length;i++){//搜索*a*格式
int temp=1;
for(int j=1;;j++){
if(i-j<0||i+j>=length)break;
if(s[i-j]!=s[i+j])break;
temp+=2;
}
Max=max(Max,temp);
}
for(int i=0;i<length;i++){//搜索*aa*格式
int temp=0;
for(int j=0;;j++){
if(i-j<0||i+j+1>=length)break;
if(s[i-j]!=s[i+1+j])break;
temp+=2;
}
Max=max(Max,temp);
}
printf("%d\n",Max);
return 0;
}