GPLT L2-008. 最長對稱子串

題目:最長對稱子串

思路:枚舉每個位置,從每個位置的左右同時開始進行查找相等累計個數,分奇數和偶數倆種情況,篩選最大值即可。

代碼:

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int main()
{
    char str[1005];
    while(gets(str)!=NULL){
        int len = strlen(str),l,r,lcnt,rcnt,ans = 0;
        for(int i=0;i<len;i++){
            l = i-1;r = i+1;lcnt = 1;//奇數情況
            while(str[l] == str[r] && l>=0 && r<len){l--;r++;lcnt+=2;}
            l = i;r = i+1;rcnt = 0;//偶數情況
            while(str[l] == str[r] && l>=0 && r<len){l--;r++;rcnt+=2;}
            ans = max(ans,max(lcnt,rcnt));
        }
        printf("%d\n",ans);
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章