LeetCode OJ 05 Longest Palindromic Substring

来源:互联网 发布:wifi跑字典软件 编辑:程序博客网 时间:2024/06/06 08:34

题目: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.

难度:medium


思路:这个解题法有很多,暂时选择的是时间复杂度为O(n)的Manacher 算法。详情见http://www.cnblogs.com/daoluanxiaozi/p/longest-palindromic-substring.html


代码:

class Solution {public:    string stringProcess(string s){        if(s.length()==0)            return "$*";        else{            string result="$#";            for(int i=0;i<s.length();i++)                result+=(s.substr(i,1)+"#");            result+="*";            return result;        }            }    string longestPalindrome(string s) {        string sChange=stringProcess(s);        const int length = sChange.length();        int p[length];        int max=0;        int id=0;                for(int i=1;i<length-1;i++){            int i_opposit=2*id-i;            if(max>i){                p[i]=min(p[i_opposit],p[max-i]);            }            else p[i]=0;            while(sChange[p[i]+1+i]==sChange[i-1-p[i]])                p[i]++;            if(p[i]+i>max){                max=p[i]+i;                id=i;            }        }                //find the max in P        int maxvalue=0;        int maxPos=0;               for(int i=1;i<length-1;i++){            if(p[i]>maxvalue){                maxvalue=p[i];                maxPos=i;            }        }        return s.substr((maxPos-1-maxvalue)/2,maxvalue);            }};


0 0