LeetCode 214. 最短回文串

LeetCode 214. 最短回文串
在这里插入图片描述
Manacher算法

const int N = 1e5 + 10;
class Solution {
public:
    char str[N];
    int p[N];
    int n;
    int maxlen = 0;
    void init(string s)
    {
        n = 0;
        str[n ++] = '$';
        str[n ++] = '#';
        for(int i = 0; i < s.size(); i ++)
            str[n ++] = s[i], str[n ++] = '#';
        str[n ++] = '^';
    }
    int manacher()
    {
        int mid = 0, mr = 0;
        for(int i = 1; i < n; i ++)
        {
            if(i < mr) p[i] = min(p[2 * mid - i], mr - i);
            else p[i] = 1;

            while(str[i + p[i]] == str[i - p[i]])
                p[i] ++;
            if(p[i] + i > mr)
            {
                mr = p[i] + i;
                mid = i;
            }
            maxlen = max(maxlen, p[i] - 1);
        }
        return mid;
    }
    string shortestPalindrome(string s) {

        init(s);
        cout << str << endl;
        int mid = manacher();
        // cout << maxlen << endl;
        int pre_max = 0;
        for(int i = 0; i < n; i ++)
            if(p[i] == i) 
                pre_max = i;
        cout << pre_max - 1 <<endl;
        string t = s.substr(pre_max - 1);
        reverse(t.begin(), t.end()); 
        s = t + s;
        return s;
    }
};

字符串Hash

const int N = 1e5 + 10;
typedef unsigned long long ULL;
class Solution {
public:
    ULL p[N], pow = 131;
    string shortestPalindrome(string s) {
        int n = s.size();
        p[0] = 1;
        for(int i = 1; i < n; i ++)
            p[i] = p[i - 1] * pow;
        
        ULL sin = 0, cos = 0; //正向hash值和反向hash值一样则为回文串
        int maxstr = -1;
        for(int i = 0; i < n; i ++)
        {
            sin = sin * pow + s[i];
            cos = cos + s[i] * p[i];
            // cout << sin <<" " << cos << endl;
            if(sin == cos)
                maxstr = i;
        }
        string t = s.substr(maxstr + 1);
        // cout << t << endl;
        reverse(t.begin(), t.end());
        return t + s;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值