显然,我们有一个朴素做法。
枚举回文串长度,再枚举起点,判断是否为回文串。
设字符串长度为 ,则时间复杂度为 。
但在此题中,,于是暴力做法可以通过!
难点在判断回文串,但只需要对于长度奇偶性分类判断即可。
#include <bits/stdc++.h>
using namespace std;
string s;
inline bool check (int st, int ed, int len) {//判断回文串
//st:起点,ed:终点,len:长度
while (s[st] == s[ed]) {
st ++, ed --;
if (st > ed) {
//字符串为偶数时,若为回文串,st会大于ed,可手推。
return true;
}
}
if (len % 2 == 1 && ed - st + 1 == 1) {
//字符串为奇数时,若为回文串,st与ed之间会隔一个字符。
return true;
}
else {
return false;
}
}
int main () {
cin >> s;
for (int len = 2; len <= s.size(); len ++) {//枚举长度。
for (int i = 0; i <= s.size(); i ++) {//枚举起点。
if (i + len - 1 > s.size()) {
break;
}
if (check (i, i + len - 1, len) == true) {
cout << len;
return 0;
}
}
}
cout << -1;
return 0;
}