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

leetcode[5]Longest Palindromic Substring

时间:2015-02-10 15:06:02      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.

class Solution {
public:
    string preProcess(string s)
    {
        string res;
        int n=s.length();
        if(0==n)
        {
            res="~@";
            return res;
        }
        res="~";
        for(int i=0;i<n;i++)
        res+="#"+s.substr(i,1);
        res+="#@";
        return res;
        
    }
    string longestPalindrome(string s) {
        string T=preProcess(s);
        int n=T.length();
        int *p=new int[n];
        int C=0;
        int R=0;
        for(int i=1;i<n-1;i++)
        {
            int i_mirror=2*C-i;
            p[i]=(R>i)?min(R-i,p[i_mirror]):0;
            while(T[i-p[i]-1]==T[i+p[i]+1])
            {
                p[i]++;
            }
            if(i+p[i]>R)
            {
                R=i+p[i];
                C=i;
            }
        }
        int maxlen=0;
        int center=0;
        for(int i=1;i<n-1;i++)
        {
            if(p[i]>maxlen)
            {
                maxlen=p[i];
                center=i;
            }
        }
        delete []p;
        return s.substr((center-1-maxlen)/2,maxlen);
    }
};

 

leetcode[5]Longest Palindromic Substring

标签:

原文地址:http://www.cnblogs.com/Vae98Scilence/p/4283719.html

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