PAT L2-008. 最长对称子串(25) (暴力,Manacher算法和DP解决)

来源:互联网 发布:淘宝关键词热度 编辑:程序博客网 时间:2024/06/07 14:21

L2-008. 最长对称子串

时间限制
100 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
陈越

对给定的字符串,本题要求你输出最长对称子串的长度。例如,给定"Is PAT&TAP symmetric?",最长对称子串为"s PAT&TAP s",于是你应该输出11。

输入格式:

输入在一行中给出长度不超过1000的非空字符串。

输出格式:

在一行中输出最长对称子串的长度。

输入样例:
Is PAT&TAP symmetric?
输出样例:
11
原题链接:https://www.patest.cn/contests/gplt/L2-008

1000的长度,100ms,o(N^2)的复杂度是可以过的,那就暴力枚举吧,

每次枚举起点和终点没如果此子串是回文串,那终点-起点+1即为回文串的长度,即可求出最大长度.

中间有个小问题,看代码注释.

AC代码:

#include <iostream>#include <cstring>#include <algorithm>using namespace std;const int maxn=1000+5;char a[maxn];int getMax(int x,int y){//注:下面结束条件,必须为i<=j!!!;//当此字符串长度为偶数是会有问题//01234//54321for(int i=x,j=y; i<=j; i++,j--){if(a[i]!=a[j])return 0;}return y-x+1;}int main(){while(gets(a)){int len=strlen(a);int maxx=0;for(int i=0; i<len; i++){for(int j=i; j<len; j++){maxx=max(maxx,getMax(i,j));}}cout<<maxx<<endl;}return 0;}

网上还有高手用了o(N)的时间复杂度解决此问题:

即(Manacher)算法:https://www.cnblogs.com/biyeymyhjob/archive/2012/10/04/2711527.html

DP解决:http://blog.csdn.net/yjf3151731373/article/details/51423812


0 0