PAT 1040 Longest Symmetric String (回文)

 Given a string, you are supposed to output the length of the longest symmetric sub-string. For example, given Is PAT&TAP symmetric?, the longest symmetric sub-string is s PAT&TAP s, hence you must output 11.

Input Specification:

 Each input file contains one test case which gives a non-empty string of length no more than 1000.

Output Specification:

 For each test case, simply print the maximum length in a line.

Sample Input:

Is PAT&TAP symmetric?

Sample Output:

11

题意:在给定字符串中找出最长的回文子串,并输出其长度

代码

#include<iostream>
#include<cstdio>
using namespace std;
int Maxl,Length;
void Find(string str,int Start,int End)
{
    int Len=End-Start+1;
    while(Start<=End)
    {
        if(str[Start]!=str[End])
            return ;
        Start+=1; End-=1;
    }
    if(Len>Maxl) Maxl=Len;
}
int main()
{
    string str;
    getline(cin,str);
    Length=str.size();
    Maxl=1;
    for(int i=0;i<Length;i++)
    {
        for(int k=i+1;k<Length;k++)
        {
            if(str[i]==str[k])
              Find(str,i,k);
        }
    }
    cout<<Maxl;
    return 0;
}

 

猜你喜欢

转载自blog.csdn.net/ZCMU_2024/article/details/84798118