基准时间限制:1 秒 空间限制:131072 KB 分值: 0
难度:基础题
回文串是指aba、abba、cccbccc、aaaa这种左右对称的字符串。
输入一个字符串Str,输出Str里最长回文子串的长度。
Input
输入Str(Str的长度 <= 1000)
Output
输出最长回文子串的长度L。
Input示例
daabaac
Output示例
5
相关问题
想法:从两边扩展,分为长度为奇数的回文串和偶数的回文串
代码:
#include<stdio.h>
#include<string.h>
char s[10010];
int main()
{
gets(s);
int len=strlen(s);
int i,j;
int count,maxx=-1;
for(i=0;i<len;i++)
{
count=0;
for(j=0;j<=i&&i+j<len;j++)
{
if(s[i+j]!=s[i-j])
break;
count=2*j+1;
if(maxx<count)
maxx=count;
}
count=0;
for(j=0;j<=i&&j+i+1<len;j++)
{
if(s[i+j+1]!=s[i-j])
break;
count=2*j+2;
if(maxx<count)
maxx=count;
}
}
printf("%d\n",maxx);
return 0;
}
#include<string.h>
char s[10010];
int main()
{
gets(s);
int len=strlen(s);
int i,j;
int count,maxx=-1;
for(i=0;i<len;i++)
{
count=0;
for(j=0;j<=i&&i+j<len;j++)
{
if(s[i+j]!=s[i-j])
break;
count=2*j+1;
if(maxx<count)
maxx=count;
}
count=0;
for(j=0;j<=i&&j+i+1<len;j++)
{
if(s[i+j+1]!=s[i-j])
break;
count=2*j+2;
if(maxx<count)
maxx=count;
}
}
printf("%d\n",maxx);
return 0;
}