PAT甲级练习1040. Longest Symmetric String (25)

来源:互联网 发布:交大软件学院 编辑:程序博客网 时间:2024/05/20 21:59

1040. Longest Symmetric String (25)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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.

Input Specification:

Each input file contains one test case which gives a non-empty string of length no more than 1000.

Output Specification:

For each test case, simply print the maximum length in a line.

Sample Input:
Is PAT&TAP symmetric?
Sample Output:
11
考虑的时候分成偶数和奇数两个情况,比较对称的字符是否相同

#include <iostream>#include <cstdio>#include <algorithm>#include <vector>#include <map>#include <set>#include <string>#include <string.h>using namespace std;const int MAX=1e3+10;char s[MAX];int main(){int n, j, k, sum, maxs=1;gets(s);n = strlen(s);for(int i=1; i<n-1; i++){//奇数情况j = k = i; sum=1;while(j && k<n){if(s[j-1]!=s[k+1]) break;else sum += 2, j--, k++;}if(sum>maxs) maxs = sum;}for(int i=0; i<n; i++){//偶数情况j = i, k = i + 1; sum=0;while(j>=0 && k<n){if(s[j]!=s[k]) break;else sum += 2, j--, k++;}if(sum>maxs) maxs = sum;}printf("%d", maxs);cin>>n;return 0;}

0 0