L2-008 最长对称子串 (25 分)
对给定的字符串,本题要求你输出最长对称子串的长度。例如,给定Is PAT&TAP symmetric?
,最长对称子串为s PAT&TAP s
,于是你应该输出11。
输入格式:
输入在一行中给出长度不超过1000的非空字符串。
输出格式:
在一行中输出最长对称子串的长度。
输入样例:
Is PAT&TAP symmetric?
输出样例:
11
思路
数据量不大,可以直接暴力做。遍历一遍字符串,每次以第 i i i个字符为对称轴,组成长度为奇数和偶数的字符串。
更好的方法还有dp和Manacher法,具体可见某大佬的博客
AC代码
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <set>
#include <vector>
#include <queue>
using namespace std;
const int maxn = 1010;
char s[maxn];
int main() {
// freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
scanf("%[^\n]", s);
int len = strlen(s);
int ans = 1;
for(int i = 0; i < len; i++) {
//构成长度为奇数的回文串
for(int j = 0; i - j >= 0 && i + j < len; j++) {
if(s[i - j] != s[i + j])
break;
if(2 * j + 1 > ans)
ans = 2 * j + 1;
}
//构成长度为偶数的回文串
for(int j = 0; i - j >= 0 && i + j + 1 < len; j++) {
if(s[i - j] != s[i + j + 1])
break;
if(2 * j + 2 > ans)
ans = 2 * j + 2;
}
}
printf("%d\n", ans);
return 0;
}