Leetcode242: Shortest Palindrome

243 篇文章 0 订阅

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

class Solution {
public:
    bool isPalindrome(string s, int start, int end)
    {
        while(start<end)
        {
            if(s[start] != s[end])  return false;
            start++;    end--;
        }
        return true;
    }
    string shortestPalindrome(string s) {
        int pos = s.length()-1;
        if(pos==0)  return s;
        for(; pos>0; pos--)
            if(s[pos]==s[0] && isPalindrome(s, 0, pos)) break;
        string res;
        for(int i = s.length()-1; i > pos; i--)
            res.push_back(s[i]);
        res+=s;
        return res;
    }
};

这种方法时间复杂度O(n2),提交超时。而求最长回文的manacher算法时间复杂度是O(n)。

class Solution {
public:
    int longestPalindrom(string s) {
        string s1;
        s1.resize(2 * s.length() + 2);
        int idx = 0;
        s1[idx++] = '$';
        s1[idx++] = '#';
        for (char a : s) {
            s1[idx++] = a;
            s1[idx++] = '#';
        }
        vector<int> p(s1.length(), 0);
        int res = 0;
        for (int id = 0, i = 1; i < s1.length(); ++i) {
            if (i < id + p[id]) p[i] = min(p[2 * id - i], id + p[id] - i);
            else p[i] = 1;
            while (s1[i + p[i]] == s1[i - p[i]]) ++p[i];
            if (id + p[id] < i + p[i]) id = i;
            if (p[i] == i) res = max(res, i);
        }
        return res - 1;
    }
    
    string shortestPalindrome(string s) {
        int pos = longestPalindrom(s);
        string res;
        for (int i = s.length() - 1; i >= pos; --i) res.push_back(s[i]);
        return res + s;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值