Skip to content

Instantly share code, notes, and snippets.

@leifwalsh
Created October 9, 2010 03:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leifwalsh/617854 to your computer and use it in GitHub Desktop.
Save leifwalsh/617854 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#define MAX(x, y) (((x) > (y)) ? (x) : (y))
int main(void)
{
static char input[] = "FourscoreandsevenyearsagoourfaathersbroughtforthonthiscontainentanewnationconceivedinzLibertyanddedicatedtothepropositionthatallmenarecreatedequalNowweareengagedinagreahtcivilwartestingwhetherthatnaptionoranynartionsoconceivedandsodedicatedcanlongendureWeareqmetonagreatbattlefiemldoftzhatwarWehavecometodedicpateaportionofthatfieldasafinalrestingplaceforthosewhoheregavetheirlivesthatthatnationmightliveItisaltogetherfangandproperthatweshoulddothisButinalargersensewecannotdedicatewecannotconsecratewecannothallowthisgroundThebravelmenlivinganddeadwhostruggledherehaveconsecrateditfaraboveourpoorponwertoaddordetractTgheworldadswfilllittlenotlenorlongrememberwhatwesayherebutitcanneverforgetwhattheydidhereItisforusthelivingrathertobededicatedheretotheulnfinishedworkwhichtheywhofoughtherehavethusfarsonoblyadvancedItisratherforustobeherededicatedtothegreattdafskremainingbeforeusthatfromthesehonoreddeadwetakeincreaseddevotiontothatcauseforwhichtheygavethelastpfullmeasureofdevotionthatweherehighlyresolvethatthesedeadshallnothavediedinvainthatthisnationunsderGodshallhaveanewbirthoffreedomandthatgovernmentofthepeoplebythepeopleforthepeopleshallnotperishfromtheearth";
int i, best_idx;
static const int n = sizeof input;
int *palin_lens = malloc((sizeof palin_lens[0]) * n);
for (i = 0; i < n; ++i) {
palin_lens[i] = 1;
}
for (i = 0; i < n; ++i) {
if (((i - 1) < 0) || ((i + palin_lens[i]) >= n)) {
continue;
}
if (input[i - 1] == input[i + palin_lens[i]]) {
if (palin_lens[i] + 2 > palin_lens[i - 1]) {
palin_lens[i - 1] = palin_lens[i] + 2;
i = 0;
}
}
}
best_idx = -1;
for (i = 0; i < n; ++i) {
if (best_idx < 0 || palin_lens[i] > palin_lens[best_idx]) {
best_idx = i;
}
}
input[best_idx + palin_lens[best_idx]] = '\0';
printf("%s\n", &input[best_idx]);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment