码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript回文数

时间:2017-07-15 10:01:30      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:middle   compare   i++   let   回文数   int   always   with   string   

 基本解决方案

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回文数

标签:middle   compare   i++   let   回文数   int   always   with   string   

原文地址:http://www.cnblogs.com/littlewriter/p/7181399.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!