HDU 3068 最长回文 Manacher

#include<iostream>
#include<string>
using namespace std;

string s;

int min(int a, int b)
{
    return a>b ? b : a;
}

int max(int a, int b)
{
    return a>b ? a : b;
}

int Manacher()
{
    if(s.length() == 0) return 0;
    int len = (int)(s.length()*2+1);
    char *cArry = new char[len];
    int *pArry = new int[len];
    for(int i = 0; i < len; i++)
        cArry[i] = i&1 ? s[(i-1)/2] : '#';
    int R = -1;
    int C = -1;
    int maxn = 0;
    for(int i = 0; i < len; i++)
    {
        pArry[i] = i > R ? 1 : min(pArry[2*C-i], R-i);
        while(i+pArry[i] < len && i-pArry[i] > -1)
        {
            if(cArry[i+pArry[i]] == cArry[i-pArry[i]]) pArry[i]++;
            else break;
        }
        if(i+pArry[i] > R)
        {
            R = i+pArry[i];
            C = i;
        }
        maxn = max(maxn, pArry[i]);
    }
    delete[] cArry;
    delete[] pArry;
    return maxn-1;
}

int main()
{
    while(getline(cin, s))
        if(s.length() != 0)
            printf("%d\n", Manacher());
    getchar();
    return 0;
}
上一篇:迭代器模式


下一篇:字符串 Manacher 计算最长回文子串