Longest Palindromic Substring

char* longestPalindrome(char* s) {
    int i;
    int id = 0, mx = 0, imax = 0;
    int p[2000] = {0};
    int len = strlen(s);
    char *str = (char*)malloc(2*len+2);
    memset(str, 0, 2*len+2);
    for(i = 0; i <= 2*len; i += 2)
        str[i] = '#';
    for(i = 0; i < len; i++)
        str[2*i+1] = s[i];
    for(i = 0; i <= 2*len; i++) {
        if(mx > i)
            p[i] = mx-i+1<p[2*id-i]? mx-i+1:p[2*id-i];
        else
            p[i] = 1;
        for(; i-(p[i]-1) > 0 && i+(p[i]-1) <= 2*len && str[i-p[i]] == str[i+p[i]]; p[i]++);
        if(i+(p[i]-1) > mx) {
            id = i;
            mx = i+(p[i]-1);
        }
        if(p[i] > p[imax])
            imax = i;
    }
    char *sub = (char*)malloc(p[imax]);
    memset(sub, 0, p[imax]);
    memcpy(sub, s+(imax-p[imax]+1)/2, p[imax]-1);
    free(str);
    return sub;
}



你可能感兴趣的:(Longest Palindromic Substring)