Skip to content

Instantly share code, notes, and snippets.

@w3cj
Last active May 25, 2016 01:20
Show Gist options
  • Save w3cj/6357ebc7025b92ebca0094d04914a1d1 to your computer and use it in GitHub Desktop.
Save w3cj/6357ebc7025b92ebca0094d04914a1d1 to your computer and use it in GitHub Desktop.
// By Alex https://github.com/AlexVotry
// reverse the string
// temp variable
// split - turns the string into an array
// reverse - built in function on array
// join - turns an array into a string with a given delimiter ''
// compare to original string
// if equal return True else return false
// By Devany https://github.com/devanymoe
// recursion!!
// BASE CASE
// length 1 - last char - is a palindrome
// length 2 - last 2 equal - then palindrome
// compare first and last letter
// if equal
// remove first and last letter from array
// DO IT AGAIN!
// if not
// not a palindrome
/* Created by David Adams December 02 2015
https://github.com/gSchool/DailyProgrammer/blob/master/03_palindrome/solutions/DTA.js
*/
function palindrome(phrase) {
phrase = sanitize(phrase);
if (phrase[0] != phrase[phrase.length - 1]) {
return false;
}
return phrase === reverse(phrase);
}
// Total: O(n + n + n) = O(n)
function reverse(string) {
// split - O(n)
// reverse - O(n)
// split - O(n)
return join.split('').reverse().join('');
/* another way to reverse - more efficient */
// O(n)
// var revString = '';
// for (var i = string.length - 1; i >=0; i--) {
// revString += string[i];
// }
// return revString;
}
// Total: O(n + n) = O(n)
function sanitize(string) {
// split - O(n)
// split - O(n)
return string.toLowerCase().replace(/\s/g, '');
}
// Big O
O(n) + O(n) + O(n) + O(n) + O(n)
O(5 * n) = O(n)
console.log(palindrome("poop"));
console.log(palindrome("Alula"));
console.log(palindrome("A but tuba"));
console.log(palindrome("Not a palindrome"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment