1040. Longest Symmetric String (25)

来源:互联网 发布:什么是淘宝登录密码 编辑:程序博客网 时间:2024/06/06 00:27

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

求出最大的对称字符串,为了简化处理,在字符与字符之间和字符串的前后都插入‘#’,如果不这样做要考虑两种情况,比如121和1221,加上‘#’后就变成‘#1#2#1#’和‘#1#2#2#1#’,直接算每个字符串两边相等的字符数就行了,最后为了使第一个不越界,在字符串前再加上‘@’。


代码:

#include <iostream>#include <vector>#include <cstring>#include <cstdlib>#include <cstdio>using namespace std;int main(){string s;getline(cin,s);string t="@#";for(int i=0;i<s.size();i++){t=t+s[i]+'#';}//cout<<t<<endl;int n=t.size();int Max=0;for(int i=1;i<n;i++){int a=1,count=0;while(t[i+a]==t[i-a]) {count++;a++;}Max=max(count,Max);}cout<<Max<<endl;}



0 0