回文数 找最长回文子串

/*
Catcher是MCA国的情报员,他工作时发现敌国会用一些对称的密码进行通信,比如像这些ABBA,ABA,A,123321,但是他们有时会在开始或结束时加入一些无关的字符以防止别国破解。比如进行下列变化 ABBA->12ABBA,ABA->ABAKK,123321->51233214 。因为截获的串太长了,而且存在多种可能的情况(abaaab可看作是aba,或baaab的加密形式),Cathcer的工作量实在是太大了,他只能向电脑高手求助,你能帮Catcher找出最长的有效密码串吗?
*/

// OJ6_1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
/*
#include <iostream>
using namespace std;
int Maxsubstr(char a[],char b[])
{
    int start1,start2;
    int count=0,Max=0;
    for(int i=0;a[i]!='\0';i++)
        for(int j=0;b[j]!='\0';j++)
        {
            start1=i;start2=j;
            while(a[start1]==b[start2] && start1<strlen(a) && start2<strlen(b))
            {
                start1++;
                start2++;
                count++;
            }
            if(count>Max)
                Max=count;
            count=0;
        }
        return Max;
}

char *Switch(char a[])
{
    int n=strlen(a);
    char temp;
    for(int i=0;i<n/2;i++)
    {
        temp=a[i];
        a[i]=a[n-1-i];
        a[n-1-i]=temp;
    }
    return a;
}

int main()
{
    char a[100];
    char b[100];
    char *c;
    gets(a);
    strcpy(b,a);
    c=Switch(a);
    cout<<Maxsubstr(b,c);
    return 0;
}
*/

# include<stdio.h>
# include<string.h>

int main(void)
{
    char a[300];
    int i,j,max,num,m;
    while(gets(a))
    {
        max = num = 0;
        m = strlen(a);
        for(i=0;i<m;i++)
        {
            for(j=0;i-j>=0 && i+j<m;j++)         //对奇数的处理
            {
                if(a[i-j]!=a[i+j])  break;
                if(2*j+1>max) max = 2*j+1;
                //12321,该字符串回文数为5
            }
            for(j=0;i-j>=0 && i+j+1<m;j++)   //对回文数是偶数的处理
            {
                if(a[i-j]!=a[i+j+1])  break;
                if(2*j+2>max) max = 2*j+2;

                if(a[i+j+1+1]=='\0'&&max>=m-i) i=m;//输入字符串123321,即a={1,2,3,3,2,1}回文数为6,

            }

        }
        printf("%d\n",max);
        memset(a,0,sizeof(a));
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值