4. 最长回文子串(Manacher算法)

中心扩展法

#include 
#include 
#define INF 0x7fffffff
#define max(x, y) x > y ? x : y

using namespace std;

int LongestPalindrome(string str)
{
    int len = str.size();
    if(len == 0)
        return 0;

    int cnt = 0;
    int max = -INF;

    //回文子串长度为奇数
    for(int i = 0; i < len; ++i)
    {
        for(int j = 0; i-j>=0 && i+j max)
            max = cnt;
    }

    //回文子串长度为偶数
    for(int i = 0; i < len; ++i)
    {
        for(int j = 0; i-j>=0 && i+j+1 < len; ++j)
        {
            if(str[i-j] != str[i+j+1])
                break;
            cnt = 2 * j + 1;
        }

        if(cnt > max)
            max = cnt;
    }

    return max;
}

int main()
{
    freopen("in.txt", "r", stdin);

    string str;

    while(cin >> str)
    {
        cout << LongestPalindrome(str) << endl;
    }

    return 0;
}

输出最长回文子串

#include 
#include 
#define INF 0x7fffffff
#define max(x, y) x > y ? x : y

using namespace std;

void printLongestPalindrome(string str)
{
    int len = str.size();
    if(len == 0)
        return;

    int cnt = 0;
    int max = -INF;
    int pos, offset, tp, to;

    //回文子串长度为奇数
    for(int i = 0; i < len; ++i)
    {
        for(int j = 0; i-j>=0 && i+j max)
        {
            max = cnt;
            pos = tp;
            offset = to;
        }
    }

    //回文子串长度为偶数
    for(int i = 0; i < len; ++i)
    {
        for(int j = 0; i-j>=0 && i+j+1 < len; ++j)
        {
            if(str[i-j] != str[i+j+1])
                break;
            cnt = 2 * j + 1;

            tp = i;
            to = j;
        }

        if(cnt > max)
        {
            max = cnt;
            pos = tp;
            offset = to;
        }
    }

    for(int i = pos-offset; i <= pos+offset; ++i)
        cout << str[i];

    cout << endl;
}

int main()
{
    freopen("in.txt", "r", stdin);

    string str;

    while(cin >> str)
    {
        printLongestPalindrome(str);
    }

    return 0;
}

你可能感兴趣的:(4. 最长回文子串(Manacher算法))