5. Longest Palindromic Substring

寻找最长回文子串——Manacher 算法,时间复杂度是O(n)
网上看到的资料中感觉这一篇是讲的最清楚的:最长回文子串——Manacher 算法 - 曾会玩 - SegmentFault


下面说明一下可能存在的一个疑问:

iMaxRight的左边时,

RL[2 * pos - i] != MaxRight - i
RL[i] = min(RL[2 * pos - i], MaxRight - i)(根据对称性推出),

而当RL[2 * pos - i] == MaxRight - i
RL[i] >= MaxRight - i,需要继续扩展以得到RL[i]


贴出我的c代码,3ms

#define min(x, y) ((x) < (y) ? (x) : (y))
#define max(x, y) ((x) > (y) ? (x) : (y))

char* longestPalindrome(char* s) {
    int l = strlen(s), mxr = 0, pos1 = 0, mxl = 0, pos2 = 0;
    char s1[2 * l + 1];
    int rl[2 * l + 1];

    s1[0] = '#';
    for(int i = 0; i < l; i++){
        s1[2 * i + 1] = s[i];
        s1[2 * i + 2] = '#';
    }
    l = 2 * l + 1;
    for(int i = 0; i < l; i++){
        if(i < mxr - 1){
            rl[i] = min(rl[2 * pos1 - i], mxr - i);
        }
        else{
            rl[i] = 1;
        }
        while(i - rl[i] >= 0 && i + rl[i] < l){
            if(s1[i - rl[i]] == s1[i + rl[i]])
                rl[i]++;
            else
                break;
        }
        if(mxr < i + rl[i]){
            mxr = i + rl[i];
            pos1 = i;
        }
        if(mxl < rl[i] - 1){
            mxl = rl[i] - 1;
            pos2 = i;
        }
    }
    s[(pos2 - mxl) / 2 + mxl] = '\0';      //(pos2 - mxl) even:'#' odd:s[]
    return s + (pos2 - mxl) / 2;
}

你可能感兴趣的:(leetcode)