最长回文字串(Manacher算法)

class Solution {
public:
    string longestPalindrome(string s) {

        if(s.empty() || s.size()==1)
                 return s;
        int strLen = s.size();
        vector<char> s1(2*strLen+2,'#');       //解决奇数,偶数问题
        s1[0] = '^';                        //防止数组越界
        int i=0;
        for(int j=0; j2)
        {
            s1[2+i] = s[j];
        }
        vector<int> radius(2*strLen+2, 1);
        int idx=0, maxRight=0;
        for(int j=1; jif(j2*idx-j], maxRight-j+1);
            }
            while(radius[j]+jif(radius[j]+j>maxRight)
            {
                maxRight = j+radius[j]-1;
                idx = j;
            }

        }

        int maxLen = 0;
        for(int j=0; jif(radius[j]>maxLen)
            {
                maxLen = radius[j];
                idx = j;
            }
        }
        int left= idx-maxLen+1;
        int right = idx+maxLen-1;
        string result = "";
        while(left<=right)
        {
            if(s1[left] != '#')
            {
                result += s1[left];
            }
            left++;
        }

        return result;


    }
};

参考文献:
http://www.cnblogs.com/hujunzheng/p/5033891.html

你可能感兴趣的:(算法与数据结构)