1040. Longest Symmetric String (25)
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
解题思路:枚举,但需要把输入的字符串进行填充,abba不能通过枚举来判断为回文串,但可以通过填充,例如-1a-1b-1b-1a-1,此时就不会出现abba不是回文串了。
#include<iostream> #include<vector> #include<cstring> #include<cstdio> using namespace std; int main(){ vector<char>str; char s[1002]; gets(s); int length=strlen(s); int i,j; for(i=0;i<length;i++){ str.push_back(-1); str.push_back(s[i]); } str.push_back(-1); int size=str.size(); int max=0; for(i=1;i<size;i++){ int l,r; int length=0; for(l=i-1,r=i+1;l>=0&&r<size;l--,r++){ if(str[l]!=str[r]){ break; } length+=2; } max=max>length?max:length; } printf("%d\n",max/2); return 0; }