× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

find longest palindrome in a string with javascript

Foysal
Feb 22, 2015
<p>The client wanted to understand how to find a longest palindrome in a given string with javascript. I looked up a couple of solutions online but i found it hard to make connection with most of them so I came up with my own implementation which takes an iterative approach to solving the problem. Not sure how efficient this is to be honest but hey, it works !<br>  </p> <pre><code>function isPalindrome(s) { var rev = s.split("").reverse().join(""); return s == rev; } function longestPalind(s){ var maxp_length = 0, maxp = ''; for(var i=0; i &lt; s.length; i++) { var subs = s.substr(i, s.length); for(var j=subs.length; j&gt;=0; j--) { var sub_subs = subs.substr(0, j); if (sub_subs.length &lt;= 1) continue; //console.log('checking: '+ sub_subs); if (isPalindrome(sub_subs)) { //console.log('palindrome: '+ sub_subs); if (sub_subs.length &gt; maxp_length) { maxp_length = sub_subs.length; maxp = sub_subs; } } } } //console.log(maxp_length, maxp); return maxp; } console.log(longestPalind("abcxyzyxabcdaaa"));</code></pre> <p> </p>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus