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

Example 1:

Input: "aacecaaa"
Output: "aaacecaaa"

Example 2:

Input: "abcd"
Output: "dcbabcd"

分析

在字符串添加最少的字符得到回文数。暴力搜索的办法就是依次以每一个i为中点,查看左边的全部字符串的倒序可以在右边找到,然后再在前面补齐即可。但是这样应该会超时。

在字符串的前方添加字符组成回文串,其实就是需要找出该字符串中以0位开始已经组成的最大的回文串的长度。而回文串的特点是正序反序是相同的,可以计算s+'#' + rever(s)的next数组问题。next数组的定义就是求解前方出现的最长的重复序列长度。

Code

class Solution {
public:
    string shortestPalindrome(string s) {
        int length = s.size();
        if (length == 0)
            return "";
        
        string s1 = s;
        s1.push_back('#');
        for (int i = length - 1; i >= 0; i --)
        {
            s1.push_back(s[i]);
        }
        
        vector<int> next(2*length + 2, 0);
        next[0] = -1;
        int j = 0;
        int k = -1;
        while (j < 2*length + 1)
        {
            if (k == -1 || s1[j] == s1[k])
            {
                next[++j] = ++k;
            }
            else
            {
                k = next[k];
            }
        }
        
        string res = s;
        int start = next[2*length + 1];
        for (int i = start; i < length; i ++)
        {
            res.insert(0, 1, s[i]);
        }
        
        return res;
    }
};

运行

 Runtime: 272 ms, faster than 19.98% of C++ online submissions for Shortest Palindrome.

Memory Usage: 10.1 MB, less than 30.00% of C++ online submissions forShortest Palindrome.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值