1. 程式人生 > >天梯賽習題 L2-008. 最長對稱子串

天梯賽習題 L2-008. 最長對稱子串

對給定的字串,本題要求你輸出最長對稱子串的長度。例如,給定"Is PAT&TAP symmetric?",最長對稱子串為"s PAT&TAP s",於是你應該輸出11。

輸入格式:

輸入在一行中給出長度不超過1000的非空字串。

輸出格式:

在一行中輸出最長對稱子串的長度。

輸入樣例:
Is PAT&TAP symmetric?
輸出樣例:
11
題目連結
當子字串為偶數時,指的是i+1右邊j個字元加上i左邊j個字元。
當字串為奇數時,指的是i左邊j個字元加上i右邊j個字元加第i個字元。
所以對稱子字串必須滿足
偶數 i+1-j>0 i+j<len str[i-j+1]==str[i+j]
奇數 i-j>0 i+j<len str[i-j]==str[i+j]
當不滿足時說明此時的i不適合 跳過
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<string>
using namespace std;
int main()
{
    char str[1010];
    gets(str);
    int maxn=0,t;
    int len=strlen(str);
    for(int i=0;i<len;i++)
    {
        t=1;   //奇數時
        for(int j=1;j<=len;j++)
        {
            if(i-j<0||i+j>=len||str[i-j]!=str[i+j])
                break; //不滿足,跳過
            t+=2;
        }
        maxn=max(maxn,t);
        t=0;//偶數時
        for(int j=1;j<=len;j++)
        {
            if(i+1-j<0||i+j>=len||str[i-j+1]!=str[i+j])
                break;
            t+=2;
        }
        maxn=max(maxn,t);
    }
    cout<<maxn<<endl;
    return 0;
}