#include <stdio.h>
#include <string.h>
// Function to expand around center and return length of palindrome
int expandAroundCenter(const char *s, int left, int right) {
int L = left, R = right;
while (L >= 0 && s[R] != '\0' && s[L] == s[R]) {
L--;
R++;
}
return R - L - 1; // length of palindrome
}
// Function to find longest palindromic substring
void longestPalindrome(const char *s) {
int start = 0, maxLen = 0;
int len = (int)strlen(s);
for (int i = 0; i < len; i++) {
int len1 = expandAroundCenter(s, i, i); // odd length palindrome
int len2 = expandAroundCenter(s, i, i + 1); // even length palindrome
int currLen = (len1 > len2) ? len1 : len2;
if (currLen > maxLen) {
maxLen = currLen;
start = i - (currLen - 1) / 2;
}
}
printf("Longest palindromic substring: ");
for (int i = start; i < start + maxLen; i++) {
printf("%c", s[i]);
}
printf("\n");
}
int main() {
const char *input = "banana";
longestPalindrome(input);
return 0;
}
while (L >= 0 && s[R] != '\0' && s[L] == s[R]) { L--; R++; }
expand left and right pointers while characters match to find palindrome length
int len1 = expandAroundCenter(s, i, i);
check odd length palindrome centered at i
int len2 = expandAroundCenter(s, i, i + 1);
check even length palindrome centered between i and i+1
if (currLen > maxLen) { maxLen = currLen; start = i - (currLen - 1) / 2; }
update longest palindrome start and length if current is longer
for (int i = start; i < start + maxLen; i++) { printf("%c", s[i]); }
print the longest palindromic substring found
Longest palindromic substring: anana