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

LeetCode Longest Palindromic Substring

时间:2014-09-11 01:06:51      阅读:265      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   for   div   sp   log   

class Solution {
private:
    const char sep_char     = \1;
public:
    string longestPalindrome(string s) {
        int max_len = 0;
        int len = s.length();
        if (len <= 1) return s;
        
        string str;
        str.push_back(sep_char);
        for (int i=0; i<len; i++) {
            str.push_back(s[i]);
            str.push_back(sep_char);
        }
        int nlen = 2 * len + 1;
        vector<int> P(nlen, 0);
        
        int last_i = 0;
        int last_r = 0;
        
        int maxv = -1;
        int maxi = -1;

        for (int i=0; i<nlen; i++) {
            int p = i, q = i;
            if (i < last_r) {
                int j = 2 * last_i - i;     // (i + j) / 2 = last_i
                int slen = min(P[j], last_r - i);
                p-= slen;
                q+= slen;
            }
            
            while(p >= 0 && q < nlen && str[p] == str[q]) p--, q++;
            if (q > last_r) {
                last_r = q;
                last_i = i;
            }

            P[i] = q - i;
            
            if (P[i] > maxv) {
                maxv = P[i];
                maxi = i;
            }
        }
        return s.substr((maxi + 1 - P[maxi]) / 2, P[maxi] - 1);
    }
};

Manacher算法实现,不能懈怠

LeetCode Longest Palindromic Substring

标签:style   blog   color   io   ar   for   div   sp   log   

原文地址:http://www.cnblogs.com/lailailai/p/3965529.html

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