5-12 最长对称子串 (25分)
对给定的字符串,本题要求你输出最长对称子串的长度。例如,给定Is PAT&TAP symmetric?
,最长对称子串为s PAT&TAP s
,于是你应该输出11。
输入格式:
输入在一行中给出长度不超过1000的非空字符串。
输出格式:
在一行中输出最长对称子串的长度。
输入样例:
Is PAT&TAP symmetric?
输出样例:
11
//开始用KMP做,超时
//用暴力,过了......
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
int Next[1005];
void GetNext(char s[],int m){
int i=0,j=-1;
Next[0]=-1;
while(i<m){
while(j>-1&&s[i]!=s[j]){
j=Next[j];
}
i++;
j++;
if(s[i]==s[j]){
Next[i]=Next[j];
}
else{
Next[i]=j;
}
}
return;
}
int KMP(char s[],char t[]){//s 模式串 t 目标串
int i=0,j=0;
int m=strlen(s);
int n=strlen(t);
if(m>n){
return 0;
}
GetNext(s,m);
while(j<n){
while(i>-1&&s[i]!=t[j]){
i=Next[i];
}
i++;
j++;
if(i>=m){
return m;
}
}
return 0;
}
int main(){
int i,j,re=0,re1;
char s[1005],t[1005],temp[1005];
gets(s);
for(i=0,j=strlen(s)-1;j>=0;){
t[i++]=s[j--];
}
t[i]='\0';
for(int i=0;i<strlen(t);i++){
for(int j=i;j<strlen(t);j++){
strcpy(temp,t+i);
temp[j+1]='\0';
re1=KMP(temp,s);
re=max(re,re1);
}
}
cout<<re<<endl;
return 0;
}
#include<stdio.h>
#include<string.h>
char s[1005];
int judge(int l,int r){
for(int i=l,j=r;i<=j;i++,j--){
if(s[i]!=s[j])
return -1;
}
return r-l+1;
}
int main(){
gets(s);
int len=strlen(s);
int ans=1;
for(int i=0;i<len;i++){
for(int j=0;j<len;j++){
int tmp=judge(i,j);
if(tmp>ans)
ans=tmp;
}
}
printf("%d",ans);
return 0;
}
#include <cstdio>
#include <iostream>
using namespace std;
char s[1005];
inline int judge(int i,int j){
while(i<=j&&s[i++]==s[j--]);
if(i<=j||(s[--i]!=s[++j])){//第二种适用于 abca的情况
return 0;
}
return 1;
}
int main(){
int ans=1;
gets(s);
for(int i=0;s[i];i++){
for(int j=i+1;s[j];j++){
if(judge(i,j)){
ans=max(ans,j-i+1);
}
}
}
cout<<ans<<endl;
return 0;
}