用的Manacher法,O(n)复杂度,证明跟kmp算法一样说不清
代码基本上是参考博客链接
dp法内存不够,中心扩展法时间不够
//Manacher法
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
typedef long long ll;
#define DEBUG
const int maxn=110000*2+5,maxv=26,INF=0x3f3f3f3f,mod=100000000;
char str[maxn],s[maxn];
int rad[maxn];
int main(){
#ifdef DEBUG
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
while(cin>>str){
int len=strlen(str);
int ans=0;
memset(rad,0,sizeof(rad));
for(int i=0;i2*i]='#',s[2*i+1]=str[i];
}
s[2*len]='#';s[2*len+1]='\0';
int n=strlen(s);
for(int i=1,j=0,k;iwhile(s[i-j-1]==s[i+j+1]&&i+j+1for(k=1;k<=j&&rad[i-k]+k!=rad[i];k++){
rad[i+k]=min(rad[i-k],rad[i]-k);
}
j=max(j-k,0);
}
for(int i=0;i// printf("%d ", rad[i]);
ans=max(ans,rad[i]);
}
printf("%d\n",ans);
}
#ifdef DEBUG
fclose(stdin);
fclose(stdout);
#endif
return 0;
}
//中心扩展法
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
typedef long long ll;
#define DEBUG
const int maxn=110000+5,maxv=26,INF=0x3f3f3f3f,mod=100000000;
char str[maxn];
int main(){
#ifdef DEBUG
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
while(cin>>str){
int n=strlen(str);
int ans=1;
for(int i=0;iint j=i,k=i;
while(j>=0&&kif(str[j]==str[k]){
ans=max(ans,k-j+1);
}
}
}
for(int i=0;i1;i++){
int j=i,k=i+1;
while(j>=0&&kif(str[j]==str[k]){
ans=max(ans,k-j+1);
}
j--;k++;
}
}
printf("%d\n",ans);
}
#ifdef DEBUG
fclose(stdin);
fclose(stdout);
#endif
return 0;
}
//dp法,内存开不了那么大
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
typedef long long ll;
#define DEBUG
const int maxn=110000+5,maxv=26,INF=0x3f3f3f3f,mod=100000000;
int dp[maxn][maxn];
char str[maxn];
int main(){
#ifdef DEBUG
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
while(cin>>str){
int n=strlen(str);
int ans=1;
memset(dp,0,sizeof(dp));
for(int i=0;iif(i&&str[i-1]==str[i])dp[i-1][i]=1,ans=2;
dp[i][i]=1;
}
for(int i=3;i<=n;i++){
for(int j=0;jif(j+i-1>=n)break;
if(dp[j+1][j+i-2])dp[j][j+i-1]=1,ans=i;
}
}
printf("%d\n",ans);
}
#ifdef DEBUG
fclose(stdin);
fclose(stdout);
#endif
return 0;
}