Created
August 27, 2015 21:01
-
-
Save alucic/e7299a26a47f404b7ec9 to your computer and use it in GitHub Desktop.
Get the longest palindrome for a given string
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
// example: node palindrome.js bananas | |
var input = process.argv[2]; | |
if (!input || !input.length) { | |
return ''; | |
} | |
var longest = longestPalindrome(input); | |
console.log('Longest palindrome is: ' + longest); | |
function longestPalindrome(input) { | |
var word; | |
for (var i = input.length; i > 0; i--) { | |
for (var j = 0; j+i <= input.length; j++) { | |
word = input.slice(j, i+j); | |
if (word && mirrors(word)) { | |
return word; | |
} | |
} | |
} | |
// default to first letter | |
return input[0]; | |
} | |
function mirrors(word) { | |
return word === word.split('').reverse().join(''); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code doesn't account for whitespaces and but if you want to send a whole sentence like "Are we not drawn onward to new era" you should strip whitespaces
.replace(/ /g,'')
and use.toLowerCase()
to make it work.Another note is if you call app and give it a sentence like:
node palindrome.js This is my sentence
it will only checkThis
for palindrome.Correct way would be to call it as
node palindrome.js "This is my sentence"
and replace all whitespaces and turn your string to lowecase for comparation