Palindrome Checker

function palindrome(str) {
  //检查字符串是否回文
  //忽略大小写
  //去除空白字符标点符号等特殊字符 *#_-\\/|,.
  //a-zA-Z0-9   \\W|_
  let pureLetters = str.replace(/\\W|_/g,'').toLowerCase().split("")
  for(let i=0; i< pureLetters.length-i; i++) {
    if(pureLetters[i] !== pureLetters[pureLetters.length-1-i]){
      return false
    }
  }
  return true;
}

palindrome("eye");

监测数据:

palindrome("eye") should return a boolean. palindrome("eye") should return true. palindrome("eye") should return true. palindrome("race car") should return true. palindrome("not a palindrome") should return false. palindrome("A man, a plan, a canal. Panama") should return true. palindrome("never odd or even") should return true. palindrome("nope") should return false. palindrome("almostomla") should return false. palindrome("My age is 0, 0 si ega ym.") should return true. palindrome("1 eye for of 1 eye.") should return false. palindrome("0_0 (: /-\ :) 0-0") should return true. palindrome("five|\/|four") should return false.

别人家的孩子:

//字符串与 倒序的自己 相等,那就是回文
function palindrome(str) {
  return (
    str.replace(/[\\W_]/g, "").toLowerCase() ===
    str
      .replace(/[\\W_]/g, "")
      .toLowerCase()
      .split("")
      .reverse()
      .join("")
  );
}
//我的正则 /\\W|_/g
//此处正则 /[\\W_]/g
//for 的控制,length/2
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;
}
//两头向中间 一个字符一个字符的处理
//this solution performs at minimum 7x better, at maximum infinitely better.
//read the explanation for the reason why.
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
    if (str[front].match(/[\\W_]/)) {
      front++;
      continue;
    }
    //decrements back pointer if current character doesn't meet criteria
    if (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;
}