/**************************************************************************
*
* 5. [Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/)
*
* Given a string s, return the longest palindromic substring in s.
*
* Example 1:
* Input: s = "babad"
* Output: "bab"
* Note: "aba" is also a valid answer.
*
*
**************************************************************************/
//
//
// Approach 1: Dynamic Programming 300 ms!
// f[j][i] = 1 means s[j~i] are Palindromic
// ┌ 1 , i == j //only one
// f[j][i] = ┼ s[j] == s[i] , i = j + 1 //only two element
// └ s[j] == s[i] && f[j+1][i-1] == 1 , i > j + 1 //more than two
//
char * longestPalindrome(char * s){
int len = 1;
int start = 0;
int n = strlen(s);
if (n < 1) return NULL;
char **f = (char **)calloc(n, sizeof(char *));
for (int i = 0; i < n; i++)
f[i] = (char *)calloc(n, sizeof(char));
for (int i = 0; i < n; i++) {
f[i][i] = 1;
for (int j = 0; j < i; j++) {
f[j][i] = (s[j] == s[i] && (i == j + 1 || f[j+1][i-1])); //i,j挨着的情况无需判断f[j+1][i-1]
if (f[j][i] && len < i - j + 1) {
len = i - j + 1;
start = j;
}
}
}
for (int i = 0; i < n; i++)
free(f[i]);
free(f);
if (len < 1) return NULL;
char *substr = (char *)calloc(len + 1, sizeof(char));
memcpy(substr, &s[start], len);
return substr;
}
//
//
// Approach 2: Expand Around Center 12ms
// A palindrome can be expanded from its center.
char * longestPalindrome(char * s){
int len = 0;
int start = 0;
int n = strlen(s);
for (int i = 0; i < n; i++) {
int left = i;
int right = i;
while (right < n - 1 && s[right] == s[right+1]) right++;
while (right < n - 1 && left > 0 && s[right+1] == s[left-1]) {
left--;
right++;
}
if (len < right - left + 1) {
len = right - left +1;
start = left;
}
}
if (len < 1) return NULL;
char *substr = (char *)calloc(len + 1, sizeof(char));
memcpy(substr, &s[start], len);
return substr;
}