Check for Palindromes - What's the difference

Check for Palindromes - What's the difference
0.0 0

#1

Tell us what’s happening:
What’s the use of those both while statements in the second code??
Even in the first code we use the same method.
Is there only one difference that in one we start from the end and in the other we start from the middle?

Second Code

function palindrome(str) {
  str = str.toLowerCase().replace(/[\W_]/g, '');
  for(var i = 0, len = str.length - 1; i < len/2; i++) {
    if(str[i] !== str[len-i]) {
      return false;
    }
  }
  return true;
}

Second Code

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;

}

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36.

Link to the challenge:


#2

If I’m not mistaken, both sets of code start at the ends and move inward instead of one of them starting from the middle.

The while statements in the second code example that you mentioned is used to move the pointers front and back inward until a character matches /[a-zA-Z]/ is found (in other words, they are used to skip non-alphabetic characters) since it’s part of the challenge’s requirement to ignore them.

It is worth mentioning that if you end up studying the second block of code because of performance, you may also be interested in this thread.

I hope that helps!

EDIT: typos!


#3

Your code has been blurred out to avoid spoiling a full working solution for other campers who may not yet want to see a complete solution. In the future, if you post a passing solution to a challenge and have questions about it, please surround it with [spoiler] and [/spoiler] tags on the line above and below your solution code.

Thank you.


#4

ok, i will follow that.