1. 程式人生 > >7-64 最長對稱子串 (25 分)

7-64 最長對稱子串 (25 分)

7-64 最長對稱子串 (25 分)

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

輸入格式:

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

輸出格式:

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

輸入樣例:

Is PAT&TAP symmetric?

輸出樣例:

11
#include <stdio.h>

int count (char *str);
int main () {
    char str[1001];
    gets(str);
    int cnt = count(str);
    printf ("%d",cnt);

    return  0  ;
}

int count (char *str){
    int i,j,t1,t2,result=1,t;			//result 結果最小為1 
    for ( i=0; i<strlen(str)-1; i++ ){
        for ( j=strlen(str)-1; j>=i; j--){
                if (str[i] == str[j]){      //從後往前找一個相同字元
                    t1 =  i;
                    t2 = j;
                    while(t1 <= t2){        //判斷是否是對稱字串
                        if ( str[++t1] != str[--t2] )       
                            break;
                    }
                    if ( t1>=t2 && j-i+1 > result )            //找到對稱字串計算長度並且長度更長 
                        result = j - i + 1;
                }
            
        }
    }
        return result ;


}