首页 > 代码库 > 最长回文子串

最长回文子串

Manacher算法:

  参考资料:https://segmentfault.com/a/1190000003914228

       http://www.cnblogs.com/biyeymyhjob/archive/2012/10/04/2711527.html

代码:

#include <iostream>
#include <stdio.h>
#include <cstring>
#include <algorithm>
using namespace std;

const int maxn = 100000+10;
char s[maxn];
char A[maxn*2];
int B[maxn*2];

int Manacher(char s[], int len)
{
    int maxlen = 0;
    int l = 0;
    A[l++] = $;
    A[l++] = #;
    for (int i = 0; i < len; i++) {
        A[l++] = s[i];
        A[l++] = #;
    }
    A[l] = \0;
    int mx = 0, id = 0;
    for (int i = 0; i < l; i++) {
        B[i] = mx > i ? min(B[2*id-i], mx-i):1; 
        while (A[i+B[i]] == A[i-B[i]])
            B[i]++;
        if (i+B[i] > mx) {
            mx = i+B[i];
            id = i;
        }
        maxlen = max(maxlen, B[i]-1);
    }
    return maxlen;
}

int main()
{
    //freopen("1.txt", "r", stdin);
    cin >> s;
    int len = strlen(s);
    cout << Manacher(s, len);


    return 0;
}

动态规划:

  dp[i][j] = 1为回文串

  dp[i][j] = dp[i+1][j-1]   if (s[i]==s[j])

     = 0   (s[i] != s[j])

代码:

#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;

char s[1100];
int dp[1100][1100];

int main()
{
    cin >> s;
    int len = strlen(s);
    int i, k;
    int L = 0, R = 0;

    memset(dp, 0, sizeof(dp));
    dp[0][0] = 1;
    for (i = 1; i < len; i++) {
        dp[i][i] = 1;
        dp[i][i-1] = 1;
    }
    for (k = 2; k <= len; k++) {
        for (i = 0; i <= len-k; i++) {
            if (s[i] == s[i+k-1] && dp[i+1][i+k-2])
            {
                dp[i][i+k-1] = 1;
                if (R-L+1 < k) {
                    L = i;
                    R = i + k -1;
                }
            }
        }
    }
    cout << R-L+1;

    return 0;
}

 

最长回文子串