题目链接:传送门
思路:求最长回文子串,想到马拉车,但是不会,看到n只有1000,所以直接枚举中心点,有两种情况:回文串长度是奇数,或者回文串长度是偶数,o(n*n)遍历即可。
代码:
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
getline(cin , s);
int ans = 1;
for(int i = 0 ; i < s.length() ; i++) {
int cnt = 1;
for(int j = 1 ; i + j < s.length() && i - j >= 0; j++) {
if(s[i - j] != s[i + j]) {
break;
}
cnt = max(cnt , 2 * j + 1);
}
for(int j = 1 ; i + j < s.length() && i - j + 1 >= 0 ; j++) {
if(s[i - j + 1] != s[i + j]) {
break;
}
cnt = max(cnt , 2 * j);
}
ans = max(cnt , ans);
}
cout << ans << "\n";
return 0;
}