广师oj 2238 最长回文子串

来源:互联网 发布:linux 改名字命令 编辑:程序博客网 时间:2024/04/30 04:14

回文串,就是从前往后和从后往前看都是一样的字符串。那么现在给你一个字符串,请你找出该字符串中,长度最大的一个回文子串。

输入描述
有且仅有一个仅包含小写字母的字符串,保证其长度不超过5000

输出描述
有且仅有一个正整数,表示最长回文子串的长度

样本输入

abccbxyz
样本输出
4

将每个字符都当作回文串的中心,一这个字母为中心向两边比较
但要考虑两种情况:aba型,abba型;

#include <stdio.h>#include <string.h> int main(){    int x,y,z,t,num,len;    char a[5005];    scanf("%s",a);    len  =  strlen(a)-1;    num = 1;    for(x=0;x<=len;x++)    {        if(a[x-1]==a[x+1])        {            y = 1;            t = 0;            while(x+y<=len&&x-y>=0)            {                if(a[x+y]!=a[x-y])                {                    break;                }                t++;                y++;            }            if((t*2+1)>num)            num = t*2+1;        }        if(a[x]==a[x+1])        {            y = 1;            t = 0;            while(x-y>=0&&x+1+y<=len)            {                if(a[x-y]!=a[x+1+y])                {                    break;                }                t++;                y++;            }            if((t+1)*2>num)            num = (t+1)*2;        }    }    printf("%d\n",num);    return 0;}

将每个字符都作为回文串的第一个字符,并往后找,直到找到以其开头最大的回文串

#include <stdio.h>#include <string.h>int main(){    int x,y,z,t,num,len;    int tmp1,tmp2;      char a[5005];    scanf("%s",a);    len = strlen(a)-1;    num = 1;    for(x=0;x<=len;x++)    {        for(y=x+1;y<=len;y++)        {               for(tmp1=x,tmp2=y;tmp1<=tmp2;tmp1++,tmp2--)            {                  if(a[tmp1]!=a[tmp2])                      break;              }              if(tmp1>=tmp2&&y-x+1>num)              {                  num = y-x+1;             }          }       }    printf("%d\n",num);    return 0;}
原创粉丝点击