5. Longest Palindromic Substring

题意

在一个字符串中找最长回文子串

思路

manacher算法模板题
时间复杂度O(n)

代码

int len[5005];
class Solution {
public:
    string longestPalindrome(string s) {
        string temp = "$#";
        for (int i = 0; i < s.size(); i++)
        {
            temp += s[i];
            temp += '#';
        }
        temp += '!';
        
        int id = 0, mx = 0;
        int rescenter = 0, reslen = 0;
        for (int i = 1; i < temp.size()-1; i++)
        {
            len[i] = i < mx?min(len[2*id-i], mx-i):1;
            while (temp[i-len[i]] == temp[i+len[i]]) len[i]++;
            if (i+len[i] > mx)
            {
                mx = i+len[i];
                id = i;
            }
            if (len[i] > reslen)
            {
                reslen = len[i];
                rescenter = i;
            }
        }
        return s.substr((rescenter - reslen)/2, reslen-1);
    }
};

5. Longest Palindromic Substring_第1张图片

你可能感兴趣的:(leetcode)