1. 程式人生 > >2017上海金馬五校程式設計競賽 E:Find Palindrome

2017上海金馬五校程式設計競賽 E:Find Palindrome

Time Limit: 1 s

Description

Given a string S, which consists of lowercase characters, you need to find the longest palindromic sub-string. A sub-string of a string S  is another string S'  that occurs "in" S. For example, "abst" is a sub-string of "abaabsta". A palindrome is a sequence of characters which reads the same backward as forward.

Input

There are several test cases. Each test case consists of one line with a single string S (1 ≤ || ≤ 50).

Output

For each test case, output the length of the longest palindromic sub-string.

Sample Input

sasadasa
bxabx
zhuyuan

Sample Output

7
1
3

題目意思:

給你一串字元,讓你找出其中最長的迴文子串長度。

解題思路:

首先先看字串,對於第 i 個字元str[i],如果迴文子串有奇數個字元,那麼以 i 為中心向左向右擴充套件,直到發現對稱位置字元不相等,如果掃過X個字元,那麼迴文子串長度為2*X+1.

如果迴文子串有偶數個字元,對於第 i 個字元str[i]在最接近對稱軸的左邊。對於這種情況我們要從第 i 個位置開始掃描,並與第 i+1 個位置字元進行比較,在向左向右擴充套件,直到對稱位置字元不相同為止。如果掃過了X個字元,那麼迴文子串長度為2*X。

#include<iostream>  
#include<stdio.h>  
#include<algorithm>  
#include<string.h>  
#define INF 999999  
using namespace std;     
int main()  
{  
    int maxlen,i,j,len;   ///最長對稱子串長度。  
    char str[1003];  
    while(gets(str))  
    {  
        maxlen = 0;  
        len = strlen(str);  
        for(i = 0; i < len; i++)  
        {  
            ///考慮是i是奇數串的中心,以i為中心,同時往左往右擴充套件  
            for(j = 0; i-j>=0&&i+j<=len; j++)  
            {  
                if(str[i-j]!=str[i+j])  
                    break;  
                if(2*j+1>maxlen)  
                    maxlen = 2*j+1;  
            }  
            ///i是偶數串的中心  
            for(j = 0; i-j>=0&&i+j+1<len;j++)  
            {  
                if(str[i-j]!=str[i+j+1])  
                    break;  
                if(2*j+2>maxlen)  
                    maxlen = 2*j+2;  
            }  
        }  
        printf("%d\n",maxlen);  
    }  
    return 0;  
}