首页 > 代码库 > JavaScript回文数

JavaScript回文数

 基本解决方案

function palindrome(str) {  return str.replace(/[\W_]/g, ‘‘).toLowerCase() ===         str.replace(/[\W_]/g, ‘‘).toLowerCase().split(‘‘).reverse().join(‘‘);}

中间代码解决方案

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;}

 高级代码解决方案(性能最高)

function palindrome(str) {  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;}

 

JavaScript回文数