leetcode 214. Shortest Palindrome

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];
            }
        }
    }
};




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值