【Leetcode】Shortest Palindrome

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".

Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases. Thanks to @Freezen for additional test cases.

 

转载自陆草纯。

首先确认一点基本知识,如果某个字符串str是回文的,那么str == reverse(str)

因此,将s逆转之后拼接在s后面,即news=s+reverse(s),该新字符串news首尾相同的部分,即为s中以s[0]为起始的最长回文子串pres

只不过这里我不用上述的遍历来做,而用类似KMP算法求next数组来做。

在KMP算法中求next数组就是s自我匹配的过程,next[i]的值就表示s[i]之前有几个元素是与s开头元素相同的。

因此,next[news.size()]的值就表示news中首尾相同的部分的长度。接下来就好做了。

注意:当next[news.size()]的值大于s.size()时,说明重复部分贯穿了s与reverse(s),应该修正为next[news.size()]+1-s.size()

------------------------------------------------------------------------------------------------------------------------------------------------------------

 

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())
            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)
    {
        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];
            }
        }
    }
};

 

转载于:https://www.cnblogs.com/LUO77/p/5603827.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值