Last active
October 5, 2016 17:33
-
-
Save danielpowell4/0119775ceea57c8801acec113708ed45 to your computer and use it in GitHub Desktop.
Finds length of the longest substring of a string that is a palindrome in Javascript.
This file contains 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
// Palindromes are the same forwards as in reverse | |
// As an example, if the input was “I like racecars that go fast”, | |
// the largest palindrom substring (racecar) | |
// would have the length of 7. | |
var longestPalindrome = function(s){ | |
let biggest = 0; | |
const stringLength = s.length; | |
let substring; | |
for(let i = 0; i <= stringLength; i++){ | |
for(let j = i+1; j <= stringLength; j++){ | |
substring = s.slice(i,j); | |
if ( checkPalindrome(substring) ) { | |
if (substring.length > biggest) { | |
biggest = substring.length | |
} | |
} | |
} | |
} | |
return biggest | |
} | |
function checkPalindrome(string){ | |
var rev_string = string.split('').reverse().join(''); | |
return (string === rev_string) | |
} | |
/** Tests -- | |
* Test.assertEquals(longestPalindrome("a"), 1) | |
* Test.assertEquals(longestPalindrome("aa"), 2) | |
* Test.assertEquals(longestPalindrome("baa"), 2) | |
* Test.assertEquals(longestPalindrome("aab"), 2) | |
* Test.assertNotEquals(longestPalindrome("zyabyz"), 6, "Are you sure that is a palindrome?") | |
* Test.assertEquals(longestPalindrome("baabcd"), 4) | |
* Test.assertEquals(longestPalindrome("baablkj12345432133d"), 9) | |
* */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment