对给定的字符串,本题要求你输出最长对称子串的长度。例如,给定Is PAT&TAP symmetric?
,最长对称子串为s PAT&TAP s
,于是你应该输出11。
输入格式:
输入在一行中给出长度不超过1000的非空字符串。
输出格式:
在一行中输出最长对称子串的长度。
输入样例:
Is PAT&TAP symmetric?
输出样例:
11
代码长度限制 16 KB 时间限制 200 ms 内存限制 64 MB
思路分析:
对于这道题 ,看了网上的一些题解感觉十分繁琐代码冗余,我们只要在查找的时候不漏字符就行。因此我们可以分成两种情况:字串长度为奇数,或者为偶数,然后遍历s串每一个字符求出最大长度。
代码实现:
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
int res = 1;//最大长度
int main()
{
string s;
getline(cin, s);
int n = s.size();
for(int i = 0; i < n; i ++)//以s[i]这个字符向左右扩展求出最大长度
{
//字串长度为奇数
int left = i, right = i;
while(left >= 0 && right <= n - 1 && s[left] == s[right]){
left --;
right ++;
}
res = max(res, right - left - 1);
//字串长度为偶数
left = i, right = i + 1;
while(left >= 0 && right <= n - 1 && s[left] == s[right])
{
left --;
right ++;
}
res = max(res, right - left - 1);
}
cout << res << endl;
return 0;
}