首页 > 代码库 > Longest Palindromic Substring

Longest Palindromic Substring

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.

#include<iostream>
#include<string.h>
using namespace std;

string longestPalindrome(string s) {
    int len = s.size();
    int newlen = len * 2 + 1;
    char str[newlen];
    int p[newlen];
    int i, j, k, r, id;
    int maxr = 0;
    str[0] = '#';
    for(i = 1, j = 0 ;s[j] != '\0'; i++, j++) {
        str[i] = s[j];
        str[++i] = '#';
    }    
    str[i] = '\0';

    p[0] = 1;
    for(i = 1, r = 1, id = 0; i < newlen; i++) {
        if(r > i) p[i] = (p[id * 2 - i] < (r - i))?p[id * 2 - i]:(r - i);
        else p[i] = 1;
        while(str[i + p[i]] != '\0' && str[i + p[i]] == str[i - p[i]])  p[i]++;  
        if(p[i] >= maxr) {
            maxr = p[i];
            id = i;
            r = i + p[i] - 1;
        }
    }
    string str1 = s.substr((id - maxr + 1) / 2, maxr - 1);
    return str1;
}

int main() {
    string str1 = longestPalindrome("c");
    cout << str1 << endl;
}


Longest Palindromic Substring