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.
// // LongestPalindromicSubstring.c // Algorithms // // Created by TTc on 15/6/6. // Copyright (c) 2015年 TTc. All rights reserved. // #include "LongestPalindromicSubstring.h" #include <string.h> #include <stdlib.h> /** * 内层的两个 for 循环,它们分别对于以 i 为中心的,长度为奇数和偶数的两种情况,整个代码遍历中心位置 i 并以之扩展,找出最长的回文。 */ char * longestPalindrome(char* s) { int middle = 0; int n = strlen(s); int i, j, max; if (s == 0 || n < 1) return 0; max = 0; for (i = 0; i < n; ++i) { // i is the middle point of the palindrome for (j = 0; (i-j >= 0) && (i+j < n); ++j) // if the lengthof the palindrome is odd if (s[i-j] != s[i+j]) break; if (j*2-1 > max){ max = j * 2 - 1; middle = i; } for (j = 0; (i-j >= 0) && (i+j+1 < n); ++j) // for theeven case if (s[i-j] != s[i+j+1]) break; if (j*2 > max){ max = j * 2; middle = i; } } int padding = (max - 1)/2 ; int start = middle - padding; // int end = middle + padding; // printf("middle==%d pad==%d start==%d end==%d \n",middle,padding,start,end); char *result = NULL; result = (char*)malloc(sizeof(char)*(max + 1)); memcpy(result, s + start, max); result[max] = '\0'; return result; } void test_longestPalindrome(){ char s[1000] ="11aabaa"; char *max_s = longestPalindrome(s); printf("max_s===%s \n",max_s); // int max = longestPalindrome(s); // printf("max===%d",max); }