题目:输入一个字符串,求出其中最长的回文子串。
代码:最原始,很容易想到的版本
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAXN 10000
//判断是否是回文
int Valid(char* tmp){
char s[MAXN];
int len=strlen(tmp);
int i=0;
for(;i<len;i++)
if(isalpha(tmp[i]))
s[i]=toupper(tmp[i]);
s[i]='\0';
len=strlen(s);
for (i=0;i<len-1-i;i++)
if(s[i]!=s[len-1-i]) return 0;
return 1;
}
//返回阿拉伯数字长度
int PersonLen(char* tmp){
int len=0;
while(*tmp)
if(isalpha(*tmp++)) len++;
return len;
}
int main(){
char s[MAXN],tmp[MAXN],res[MAXN];
int len,i,j,first=1;
fgets(s,MAXN,stdin);
len=strlen(s)-1; //包含了换行
for(i=0;i<len;i++)
for(j=i;j<len;j++){
memcpy(tmp,s+i,j-i+1);
tmp[j-i+1]='\0';
if(!Valid(tmp)) continue;
if(first) {first=0;strcpy(res,tmp);}
else if(PersonLen(res)<PersonLen(tmp))
strcpy(res,tmp);
}
if(!first) printf("%s\n",res);
else printf("no found\n");
return 0;
}
输出:
上面方法时间复杂度是O(n^3),考虑书中的方法。以某个字符为中心,向两边搜索。考虑aba和abba两种类型
代码:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAXN 10000
int main(){
char a[MAXN],copy[MAXN],pos[MAXN];
int i=0,j=0,len,m,n,tmplen,startpos,endpos;
fgets(a,sizeof(a),stdin);
len=strlen(a);
for(;i<len;i++){
if(isalpha(a[i])){
copy[j]=toupper(a[i]);
pos[j++]=i;
}
}
//第一个字符显然是满足的
len=1;
startpos=0;
for(i=0;i<j;i++){
for(m=i-1,n=i+1;m>=0&&n<j;m--,n++){
if(copy[m]!=copy[n]) break;
tmplen=n-m+1;
if (tmplen>len){
len=tmplen;
startpos=m;
}
}
for (m=i,n=i+1;m>=0&&n<j;m--,n++){
if(copy[m]!=copy[n]) break;
tmplen=n-m+1;
if (tmplen>len){
len=tmplen;
startpos=m;
}
}
}
endpos=startpos+len-1;
for(i=pos[startpos];i<=pos[endpos];i++)
printf("%c",a[i]);
printf("\n");
return 0;
}
时间复杂度为O(n^2)
网上还介绍了一种时间复杂度为O(n)的算法,以后再写。