九度oj 题目1528:最长回文子串

题目描述:

回文串就是一个正读和反读都一样的字符串,比如“level”或者“noon”等等就是回文串。
回文子串,顾名思义,即字符串中满足回文性质的子串。
给出一个只由小写英文字符a,b,c...x,y,z组成的字符串,请输出其中最长的回文子串的长度。

输入:

输入包含多个测试用例,每组测试用例输入一行由小写英文字符a,b,c...x,y,z组成的字符串,字符串的长度不大于200000。

输出:

对于每组测试用例,输出一个整数,表示该组测试用例的字符串中所包含的的最长回文子串的长度。

样例输入:
abab
bbbb
abba
样例输出:
3
4
4

对原字符串可以做一定的预处理,以使判断更加方便,代码如下
#include <cstdio>
#include <cstdlib>
#include <cstring>

char toDo[200020];
char dealed[400020];

int main(int argc, char const *argv[])
{
    //freopen("input.txt","r",stdin);
    while(scanf("%s",toDo) != EOF) {
        int len = strlen(toDo);
        int j = 0;
        dealed[j++] = '#';
        for(int i = 0; i < len; i++) {
            dealed[j++] = toDo[i];
            dealed[j++] = '#';
        }
        dealed[j] = '';
        int max = 0;
        int cnt = 1;
        for(int i = 0; i < j; i++) {
            cnt = 1;
            for(int p = i-1, q = i+1; p >= 0 && q < j; p--, q++) {
                if(dealed[p] == dealed[q]) {
                    cnt += 2;
                }
                else {
                    break;
                }
            }
            if(max < cnt) {
                max = cnt;
            }
        }
        int ans = (max - 1)/2;
        printf("%d
",ans);
    }    
    return 0;
}

听说还有一种曼彻斯特算法,但较难理解,见网址:https://www.felix021.com/blog/read.php?2040

原文地址:https://www.cnblogs.com/jasonJie/p/5777776.html