[LeetCode] 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.

 

这道题让我们求最短的回文串,LeetCode中关于回文串的其他的题目有 Palindrome Number 验证回文数字Validate Palindrome 验证回文字符串 Palindrome Partitioning 拆分回文串Palindrome Partitioning II 拆分回文串之二 Longest Palindromic Substring 最长回文串。题目让我们在给定字符串s的前面加上最少个字符,使之变成回文串,那么我们来看题目中给的两个例子,最坏的情况下是s中没有相同的字符,那么最小需要添加字符的个数为s.size() - 1个,第一个例子的字符串包含一个回文串,只需再在前面添加一个字符即可,还有一点需要注意的是,前面添加的字符串都是从s的末尾开始,一位一位往前添加的,那么我们只需要知道从s末尾开始需要添加到前面的个数。这道题如果用brute force无法通过OJ,所以我们需要用一些比较巧妙的方法来解。这里我们用到了KMP算法,KMP算法是一种专门用来匹配字符串的高效的算法,具体方法可以参见这篇博文从头到尾彻底理解KMP。我们把s和其转置r连接起来,中间加上一个其他字符,形成一个新的字符串t,我们还需要一个和t长度相同的一位数组p,其中p[i]表示从t[i]到开头的子串的相同前缀后缀的个数,具体可参考KMP算法中解释。最后我们把不相同的个数对应的字符串添加到s之前即可,代码如下:

 

复制代码
class Solution {
public:
    string shortestPalindrome(string s) {
        string r = s;
        reverse(r.begin(), r.end());
        string t = s + "#" + r;
        vector<int> p(t.size(), 0);
        for (int i = 1; i < t.size(); ++i) {
            int j = p[i - 1];
            while (j > 0 && t[i] != t[j]) j = p[j - 1];
            p[i] = (j += t[i] == t[j]);
        }
        return r.substr(0, s.size() - p[t.size() - 1]) + s;
    }
};
复制代码

 

参考资料:

https://leetcode.com/discuss/36807/c-8-ms-kmp-based-o-n-time-%26-o-n-memory-solution

http://blog.csdn.net/v_july_v/article/details/7041827

http://www.cnblogs.com/easonliu/p/4522724.html

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值