leetcode 214. Shortest Palindrome

来源:互联网 发布:合肥网络销售诈骗案 编辑:程序博客网 时间:2024/06/05 21:02

214. Shortest Palindrome

Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation.

For example: 

Given "aacecaaa", return "aaacecaaa".

Given "abcd", return "dcbabcd".


最开始想的直接找0位开始的回文,结果TLE

class Solution {public:    string shortestPalindrome(string s)     {        int size = s.size();        if (size <= 1 || ispalindrome(s))            return s;        for (int len = size; len >= 1; len--)        {            if (ispalindrome(s.substr(0, len)))            {                string add = s.substr(len, size - len);                reverse(add.begin(), add.end());                return add + s;            }        }    }    private:    bool ispalindrome(string s)    {        string ss = s;        reverse(ss.begin(), ss.end());        return ss == s;    }};


然后网上发现了KMP的方法,学习了一波!


class Solution {public:    string shortestPalindrome(string s)     {        if(s == "")            return s;        string s2 = s;        reverse(s2.begin(), s2.end());        string news = s + "#" + s2; //很巧妙得把前后接起来,        int n = news.size();        vector<int> next(n+1);        buildNext(news, next, n);        if (next[n] > s.size())     //通过KMP算法的核心思想来得到next[n],也就是求 s的 前缀的最大回文长度            next[n] = next[n] + 1 - s.size();        string pres = s.substr(next[n]);        reverse(pres.begin(), pres.end());        return pres + s;    }        void buildNext(string& s, vector<int>& next, int n)  //KMP算法中形成next数组的标准代码    {        int k = -1;        int j = 0;        next[0] = -1;        while(j < n)        {            if(k == -1 || s[j] == s[k])            {                k ++;                j ++;                next[j] = k;            }            else            {                k = next[k];            }        }    }};