Last active
October 15, 2022 23:15
-
-
Save bumsyalao/f5e1d2d42771ea994151c20a416358b1 to your computer and use it in GitHub Desktop.
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
const longestPalindromicString = (str) => { | |
if(str.length < 1 || str == null){ | |
return ''; | |
} | |
//store longest and if find longer we update | |
let longest = ''; | |
for(let i = 0; i < str.length; i++){ | |
let oddPalindrome = expandFromCenter(str, i, i); | |
let evenPalindrome = expandFromCenter(str, i , i+ 1) | |
if(oddPalindrome.length > longest.length ){ | |
longest = oddPalindrome; | |
} | |
if(evenPalindrome.length > longest.length ){ | |
longest = evenPalindrome | |
} | |
} | |
return longest; | |
} | |
function expandFromCenter (s, left, right){ | |
let count = 0; | |
while(s[left - count] && s[left - count] == s[right + count]){ | |
count ++; | |
} | |
count--; | |
return s.slice(left - count, right+ count + 1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment