&LeetCode0005& 最長迴文子串

題目

給定一個字符串 s,找到 s 中最長的迴文子串。你可以假設 s 的最大長度爲 1000。

示例 1:

輸入: “babad”
輸出: “bab”
注意: “aba” 也是一個有效答案。

示例 2:

輸入: “cbbd”
輸出: “bb”

來源:力扣(LeetCode

思路

馬拉車算法(Manacher’s Algorithm

C++代碼

class Solution {
public:
    string longestPalindrome(string s) 
    {
        string t ="$#";
        for (int i = 0; i < s.size(); ++i) 
        {
            t += s[i];
            t += '#';
        }

        int p[t.size()] = {0}, id = 0, mx = 0, resId = 0, resMx = 0;
        for (int i = 1; i < t.size(); ++i) 
        {
            p[i] = mx > i ? min(p[2 * id - i], mx - i) : 1;
            while (t[i + p[i]] == t[i - p[i]]) ++p[i];
            if (mx < i + p[i]) 
            {
                mx = i + p[i];
                id = i;
            }
            if (resMx < p[i]) 
            {
                resMx = p[i];
                resId = i;
            }
        }
        return s.substr((resId - resMx) / 2, resMx - 1);
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章