码迷,mamicode.com
首页 > 编程语言 > 详细

LeetCode 5 Longest Palindromic Substring 最长回文子序列 manacher算法 string.substr 难度:2

时间:2015-09-01 18:28:26      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:

https://leetcode.com/problems/longest-palindromic-substring/

manacher算法:http://blog.csdn.net/ywhorizen/article/details/6629268

string longestPalindrome(string s)
{
    char ch[2001];int p[2001];
    ch[2*s.size()] = 0;
    for(int i = 0; i < 2 * s.size(); i++)
    {
        if((i & 1) == 1)ch[i] = s[(i>>1)];
        else ch[i] = ‘ ‘;
    }
    int mx = 1,id = 0;
    p[0] = 1;
    int ss = 0,se = 0;
    for(int i = 1; ch[i]; i++)
    {
        if(mx <= i)
        {
            p[i] = 1;
        }
        else
        {
            p[i] = min(p[id * 2 - i],mx - i);
        }
        while(ch[i + p[i]] == ch[i - p[i]] && i >= p[i])
        {
            p[i]++;
        }
        if(p[i] + i > mx)
        {
            id = i;
            mx = p[i] + i;
        }
        int ts = (i - p[i] + 1)/2;
        int te = (i + p[i] - 2)/2;//Attention,dont calculate ‘ ‘
        if(te - ts >se - ss){
            se = te;ss = ts;
        }
    }
    return s.substr(ss,se -ss + 1);//Attention,substr(start,len)
}

  

LeetCode 5 Longest Palindromic Substring 最长回文子序列 manacher算法 string.substr 难度:2

标签:

原文地址:http://www.cnblogs.com/xuesu/p/4776470.html

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