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

思考:利用Manacher’s ALGORITHM,可以求出,那么其他算法呢

想法:可以仿照KMP,找出以s[i]为结尾的最长回文串

代码

类似KMP,用数组指示next位置

class Solution {
public: 
    string shortestPalindrome(string s){ 
        const int len = s.size();
        string res = s; 
        if(len>1) {
            reverse(res.begin(), res.end());
            res = s + '#' + res;
            int i;
            int * T = new int[2 * len + 1];
            T[0] = 0;
            for(i = 1; i <= 2 * len; i++)
            {
                T[i] = T[i-1];
                while(T[i] > 0 && res[i] != res[T[i]]) 
                    T[i] = T[T[i]-1];

                T[i] += (res[i] ==res[T[i]]);
            }
            /*
            for(int i = 0; i <= 2 * len; i++ )
                cout<<T[i]<<" ";
            */
            return res.substr(len + 1,len - T[2*len]) + s;
        }
        return s;
    }
};

T[i]表示以s[i]结尾的回文字串长度,在“&”之前,表示在s中,s[0]::s[T[i]] 与 s[i - T[i]]::s[i]相匹配(相同)。即如果“&”后失陪(res[i]!= res[T[i]]),则往前找匹配。类似KMP的next数组。

利用Manacher算法

class Solution {
    public:
    string preProcess(string s){
        int n = s.length();
        string ret(2 * n + 1,'#');
        if(n == 0)
            return ret;
        for(int i = 0; i < n; i++)
            ret[2 * i + 1] = s[i];
        return ret;
    }
    string shortestPalindrome(string s){ 
        if(s.length() == 0) return s;
        string str = preProcess(s);
        int n = str.length(), C = 0, R = 0;
        int *p = new int[n]; 
        for(int i = 1; i < n - 1; i++){
            int sym = (C << 1) - i;
            p[i] = (R > i)? min(R - i, p[sym]): 0;
            while((p[i] + 1 + i < n) && (i - p[i] - 1 >= 0) && str[p[i] + 1 + i] == str[i - p[i] - 1 ])
                p[i]++;

            if(p[i] + i > R){
                C = i;
                R = i + p[i];
            }
        }
        int maxLen = 0;
        for(int i = n - 2; i > 0; i--)
            if(i - p[i] == 0){
                maxLen = p[i];
                break;
            }
        string temp =  s.substr(maxLen);
        reverse(temp.begin(),temp.end());
        return temp + s;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值