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<string>
#include<algorithm>
#include<bits/stdc++.h>
#include<stack>
#include<set>
#include<vector>
#include<map>
#include<queue>
#include<deque>
#include<cctype>
#include<unordered_set>
#include<unordered_map>
#include<fstream>
#include<cstring>
using namespace std;
int main() {
string s;
getline(cin, s);
int max_len = -1;
for (int i = 0; i < s.length(); i++) {
for (int j = 1; j <= s.size() - i; j++) {
string ss = s.substr(i, j);
string sss = ss;
reverse(ss.begin(), ss.end());
if (sss == ss) {
int len = sss.length();
max_len = max(max_len, len);
}
}
}
cout << max_len;
return 0;
}