最长对称子串

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值