Skip to content

Instantly share code, notes, and snippets.

@studentbrad
Last active October 23, 2019 23:29
Show Gist options
  • Save studentbrad/971ed2b67e46806b3a5b14893f7640c6 to your computer and use it in GitHub Desktop.
Save studentbrad/971ed2b67e46806b3a5b14893f7640c6 to your computer and use it in GitHub Desktop.
Find the longest palindromic substring in a string
char *longest_palindrome(char *s)
{
int n = strlen(s);
if (n < 2) return s; // Every string of length 1 or 0 is a palindrome
bool p[n][n];
memset(p, 0, sizeof(p));
int start = 0;
int length = 1;
/* The base cases */
for (int i = 0; i < n; i++)
{
p[i][i] = true;
}
for (int i = 0; i < n - 1; i++)
{
p[i][i + 1] = (s[i] == s[i + 1]);
if (p[i][i + 1])
{
start = i;
length = 2;
}
}
/* p[i, j] = true, if the substring s[i] ... s[j] is a palindrome
p[i, j] = false, otherwise. */
for (int k = 3; k < n + 1; k++)
{
for (int i = 0; i < n - k + 1; i++)
{
int j = i + k - 1;
p[i][j] = (p[i + 1][j - 1] && s[i] == s[j]);
if (p[i][j] && (k > length))
{
start = i;
length = k;
}
}
}
if (s[start + length]) s[start + length] = NULL;
return &s[start];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment