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;
    }
};

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)