题目
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
思路
寻找以每个字符为中轴点能得到的最长对称字符串,对第i个字符分两种情况:
- 奇数个字符,以 i 为中轴点
- 偶数个字符,以 i 和 i+1 之间为轴
记录当前对称字符串最大值maxNum;若加上剩下所有字符都不足以大于maxNum的话,就不用考虑了,即i应满足:i>maxNum/2-1 && i<s.size()-1-maxNum/2
代码
#include <iostream>
using namespace std;
int main(){
string s;
getline(cin, s);
int maxNum = 1;
for (int i=0; i>maxNum/2-1 && i<s.size()-1-maxNum/2; i++){
//以i为轴
int num = 1;
int j = 1;
while (i-j>=0 && i+j<s.size() && s[i-j]==s[i+j]){
num += 2;
j++;
}
if (num > maxNum){
maxNum = num;
}
//以i和i+1之间为轴
num = 0;
j = 0;
while (i-j>=0 && i+1+j<s.size() && s[i-j]==s[i+1+j]){
num += 2;
j++;
}
if (num > maxNum){
maxNum = num;
}
}
cout << maxNum << endl;
return 0;
}