1. 程式人生 > >PAT 1040 Longest Symmetric String (迴文)

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;
}