Skip to content

Instantly share code, notes, and snippets.

@bumsyalao
Last active October 15, 2022 23:15
Show Gist options
  • Save bumsyalao/f5e1d2d42771ea994151c20a416358b1 to your computer and use it in GitHub Desktop.
Save bumsyalao/f5e1d2d42771ea994151c20a416358b1 to your computer and use it in GitHub Desktop.
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