Skip to content

Instantly share code, notes, and snippets.

@alucic
Created August 27, 2015 21:01
Show Gist options
  • Save alucic/e7299a26a47f404b7ec9 to your computer and use it in GitHub Desktop.
Save alucic/e7299a26a47f404b7ec9 to your computer and use it in GitHub Desktop.
Get the longest palindrome for a given string
// 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('');
}
@alucic
Copy link
Author

alucic commented Aug 27, 2015

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 check This 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment