/substring-palindrome.js Secret
Last active
August 16, 2021 20:29
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
/*** | |
Given a string X, will return true if palindrome and false if not | |
Return value: bool | |
***/ | |
const isPalindrome = (string) => { | |
return string === string.split("").reverse().join("") | |
} | |
/*** | |
Given a string X, will return longest substring that is a palindrome, if it exists. | |
Return value: string | |
***/ | |
const pSubstring = (string) => { | |
// Is this thing already a palindrome? Then return it and call it a day. | |
if (isPalindrome(string)){ | |
return string | |
} | |
// Ok, it's not, so let's dig. | |
const possibilities = [] | |
for (let l = string.length - 1; l > 0; l--){ | |
string = string.slice(0, l); | |
for (let i = 0; i < string.length; i++){ | |
let subString = string.slice(i); | |
if (subString.length > 2 && isPalindrome(subString)){ | |
possibilities.push(subString) | |
} | |
} | |
} | |
// No matches? bail | |
if (possibilities.length === 0){ | |
return "You got nothing"; | |
} | |
// Return longest match | |
return possibilities.reduce((acc, string) => acc.length < string.length ? string : acc, possibilities[0]); | |
} | |
pSubstring("hellobablo") // "bab" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment