Skip to content

Instantly share code, notes, and snippets.

@agchou
Last active August 29, 2015 14:01
Show Gist options
  • Save agchou/3774b04702c8cada2a2d to your computer and use it in GitHub Desktop.
Save agchou/3774b04702c8cada2a2d to your computer and use it in GitHub Desktop.
Linear-ish time solution for finding longest palindrome in string.
var longestPalindrome = function (string) {
var current, i, isPalindrome, j, longest;
longest = current = '';
for (i = string.length - 2; i >= 0; i--) {
j = 1;
do {
// check for odd palindrome
if (string[i - j] === string[i + j] && string[i - j]) {
isPalindrome = true;
current = string.substring(i - j, i + j + 1);
j++;
// check for even palindrome
} else if (string[i - j + 1] === string[i + j] && string[i - j + 1]) {
isPalindrome = true;
current = string.substring(i - j + 1, i + j + 1);
j++;
// compare length of current and longest
} else {
isPalindrome = false;
if (current.length > longest.length) longest = current;
}
} while (isPalindrome);
}
return longest;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment