#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
string s;
vector<char> s2;
while (cin >> s)
{
//去除字母和数字以外的其他字符
for (int i = 0; i < s.length(); i++)
{
if ((s[i] >= '0' && s[i] <= '9') || (s[i] >= 'A' && s[i] <= 'Z') || (s[i] >= 'a' && s[i] <= 'z'))
{
s2.push_back(s[i]);
}
}
//找出所有的对称子串,并对所有子串的长度进行存储
int res = 1;
vector<int> save;
for (int i = 0; i < s2.size(); i++)
{
int l = i - 1;
int r = i + 1;
while (l >= 0 && r < s.length() && s2[l] == s2[r])
{
int len = r - l + 1;
if (len > res)
{
res = len;
}
l--;
r++;
}
save.push_back(res);
l = i;
r = i + 1;
while (l >= 0 && r < s.length() && s2[l] == s2[r])
{
int len = r - l + 1;
if (len > res)
{
res = len;
}
l--;
r++;
}
save.push_back(res);
}
sort(save.begin(), save.end());
//用来判断输入字符串中,无回文子串(回文子串长度为1)
int count = 0;
for (int i = 0; i < save.size(); i++)
{
if (save[i] == 1)
count++;
}
for (int i = save.size() - 1; i >= 0; i--)
{
if (save.size() == count) //说明save中全是1,则回文子串长度为1。
{
cout << '1' << endl;
break;
}
else if (i == save.size() - 1) //sort排序后,只用输出最大的数字,最大数字排在最后一位。
{
cout << save[i] << endl;
break;
}
}
save.clear(); //切记清空save中的元素
s2.clear();
}
return 0;
}
注意:
多组输入时,使用vector时,记得使用clear函数,清空对应vector中存储的每一组的数据,这点很重要!
华为机试被鸽了。害!还继续做题吗?