Skip to content

Instantly share code, notes, and snippets.

@masautt
Created September 6, 2019 17:57
Show Gist options
  • Save masautt/6fcd34d2806a727aacbf6395d034eefa to your computer and use it in GitHub Desktop.
Save masautt/6fcd34d2806a727aacbf6395d034eefa to your computer and use it in GitHub Desktop.
How to find longest palindrome of a string in JavaScript?
var longestPalindrome = function(s) {
if (isPalindrome(s)) {
return s;
}
var maxP = s[0];
for (var i=0; i < s.length; i++) {
var curr = s[i];
for (var j= i + 1; j < s.length; j++) {
curr += s[j];
if (isPalindrome(curr) && curr.length > maxP.length) {
maxP = curr;
}
}
}
return maxP;
};
function isPalindrome(s, i) {
return(i=i||0)<0||i>=s.length>>1||s[i]==s[s.length-1-i]&&isPalindrome(s,++i);
}
console.log(longestPalindrome('kayak tacocat racecar tattarrattat wow')); // --> "tattarrattat"
// https://jsfiddle.net/vovchuck_bogdan/yv6u9d1u/2/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment