回文数 找最长回文子串

来源:互联网 发布:怎么添加usb001端口 编辑:程序博客网 时间:2024/05/18 00:08

/*
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;}
0 0
原创粉丝点击