Created
September 6, 2019 17:57
-
-
Save masautt/6fcd34d2806a727aacbf6395d034eefa to your computer and use it in GitHub Desktop.
How to find longest palindrome of a string in JavaScript?
This file contains hidden or 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
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