码迷,mamicode.com
首页 > 其他好文 > 详细

最长回文子串

时间:2017-06-24 13:19:54      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:clu   https   algo   names   for   stream   动态规划   cstring   i++   

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;
}

 

最长回文子串

标签:clu   https   algo   names   for   stream   动态规划   cstring   i++   

原文地址:http://www.cnblogs.com/whileskies/p/7073000.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!