Last active
August 29, 2015 14:01
-
-
Save agchou/3774b04702c8cada2a2d to your computer and use it in GitHub Desktop.
Linear-ish time solution for finding longest palindrome in string.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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