字符串中最长回文字符串

给定一个字符串,求该字符串中最长的回文字符串(假设最长回文字符串仅有一个)

char* longestPalindrome(char* s) {

int len = strlen(s);
int max_left = 0;
int max_len = 1;
int left, right;
int start = 0;

while(start < len && len-start > max_len/2)
{
    left = start;
    right = start;
    while (right < len-1 && s[right+1] == s[right])//相邻的字符相等
        right++;
    start = right+1;//start的增长方法
    while (right < len-1 && left > 0 && s[right+1] == s[left-1])
    {
        right++;
        left--;
    }
    if (max_len < right-left+1)
    {
        max_left = left;
        max_len = right-left+1;
    }
}

char* res = (char*)malloc(sizeof(char)*max_len);
strncpy(res,s+max_left,max_len);
res[max_len] = '\0';

return res;

}

你可能感兴趣的:(字符串的处理)