Skip to content

Instantly share code, notes, and snippets.

@deepakkj
Created August 29, 2017 17:27
Show Gist options
  • Save deepakkj/ec2c751b86adc05cc88cd2dabfc599f2 to your computer and use it in GitHub Desktop.
Save deepakkj/ec2c751b86adc05cc88cd2dabfc599f2 to your computer and use it in GitHub Desktop.

Revisions

  1. deepakkj created this gist Aug 29, 2017.
    29 changes: 29 additions & 0 deletions palindrome2
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,29 @@
    function palindrome(str) {
    //assign a front and a back pointer
    let front = 0;
    let back = str.length - 1;

    //back and front pointers won't always meet in the middle, so use (back > front)
    while (back > front) {
    //increments front pointer if current character doesn't meet criteria
    while ( str[front].match(/[\W_]/) ) {
    front++;
    continue;
    }
    //decrements back pointer if current character doesn't meet criteria
    while ( str[back].match(/[\W_]/) ) {
    back--;
    continue;
    }
    //finally does the comparison on the current character
    if ( str[front].toLowerCase() !== str[back].toLowerCase() ) return false
    front++;
    back--;
    }

    //if the whole string has been compared without returning false, it's a palindrome!
    return true;

    }

    console.log(palindrome("race car"));