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

LeetCode:Longest Palindromic Substring

时间:2015-06-16 18:32:29      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:

problem:

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.

solution:manacher algorithm

class Solution {
public:
    string longestPalindrome(string s) {
        string pstr=preProcess(s);
        const int len=pstr.size();
        int p[len];  //用来记录回文串的长度
        p[0]=0;
        int mx=0,max_len=0,po=0,center_index=0;

        for(int i=1;i<len-1;i++)
        {
            if(mx>i)
                p[i]=min(mx-i,p[2*po-i]);
            else
                p[i]=0;
            while(pstr[i-1-p[i]]==pstr[i+1+p[i]])
               p[i]++;

            if(p[i]+i>mx)
            {
                mx=p[i]+i;
                po=i;
            }
            if(p[i]>max_len)
            {
                 max_len=p[i];
                 center_index=i;
            }

        }
      return s.substr((center_index-1-max_len)/2,max_len);
    }
    
    string preProcess(string s)
    {
       int n=s.size();
        if(n==0) return "@";
       string result="@";

       for(int i=0;i<n;i++)
       {
        result.append("#"+s.substr(i,1));  
       }
         result.append("#$");
         return result;

    }

};

 

LeetCode:Longest Palindromic Substring

标签:

原文地址:http://www.cnblogs.com/xiaoying1245970347/p/4581252.html

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