简体   繁体   English

使用JavaScript评估字符串是否是回文符的最有效方法是什么?

[英]What's the most efficient way to evaluate if a string is a palindrome using Javascript?

I'm new to Javascript and wrote the code below to determine if a string is a palindrome. 我是Java语言的新手,并在下面编写了代码,以确定字符串是否是回文。 I'm curious as to what is the most efficient way to accomplish the same task. 我很好奇什么是完成同一任务的最有效方法。

var isPalindrome = function (string) {
    var leftString = [];
    var rightString = [];

    // Remove spaces in the string and convert to an array
    var strArray = string.split(" ").join("").split("");    
    var strLength = strArray.length;

    // Determine if the string is even or odd in length, then assign left and right strings accordingly
    if (strLength % 2 !== 0) {
        leftString = strArray.slice(0, (Math.round(strLength / 2) - 1));
        rightString = strArray.slice(Math.round(strLength / 2), strLength);
    } else {
        leftString = strArray.slice(0, (strLength / 2));
        rightString = strArray.slice((strLength / 2, strLength))
    }

    if (leftString.join("") === rightString.reverse().join("")) {
        alert(string + " is a palindrome.");
    } else {
        alert(string + " is not a palindrome.")
    }

}


isPalindrome("nurses run");
function isPalindrome( s )
{
   var i = 0, j = s.length-1;
   while( i < j )
       if( s[i++].toLowerCase() != s[j--].toLowerCase() ) return false;
   return true;
}

It's not clear if you're talking about efficiency in terms of code length, or amount of computation, but this should be fairly good in both regards. 目前尚不清楚是在代码长度还是计算量方面谈论效率,但这在两个方面都应该是相当不错的。 And it takes into account non-alpha characters beside spaces as well as capitalization: 并且考虑到空格旁边的非字母字符以及大小写:

function isPalindrome(str) {
   var i, len;

   str = str.toLowerCase().replace(/[^a-z]/g, '');
   len = str.length;

   for(i = 0; i < len / 2; i += 1) {
      if(str.charCodeAt(i) != str.charCodeAt(len - i - 1)) {
         return false;
      }
   }

   return true;
}

A much shorter approach (though perhaps more computation intensive): 更短的方法(尽管可能需要更多的计算量):

function isPalindrome(str) {
   str = str.toLowerCase().replace(/[^a-z]/g, '');

   return str == str.split("").reverse().join("");
}

And if you really want that alert stuff, I'd suggest putting it in a separate function: 而且,如果您真的想要这些警报的内容,建议将其放在单独的函数中:

function isPalindromeAlert(str) {
  alert(str + "is " + (isPalindrome(str) ? "" : "not ") + "a palindrome.");
}

I think this one is lot simpler: 我认为这要简单得多:

var isPalindrome = function (string) {
    if (string == string.split('').reverse().join('')) {
        alert(string + ' is palindrome.');
    }
    else {
        alert(string + ' is not palindrome.');
    }
}

See more: Palindrome check in Javascript 查看更多: Java中的回文检查

var str = "abcba";
var len = str.Lenght;
var index = 0;

while(index <= len/2 && str[index] == str[len - index - 1]) index++;

if(index == len/2) {
    alert(string + " is a palindrome.");
}
else {
   alert(string + " is not a palindrome.");
}

You made a few unnecesary operations. 您进行了一些不必要的操作。

To be efficient, you should avoid unnecessary computations. 为了提高效率,您应该避免不必要的计算。 Ask yourself: 问你自己:

  • do you need to remove spaces? 您需要删除空格吗?
  • do you need to convert to an array? 您需要转换为数组吗?
  • do you need to allocate new objects for the left and right strings? 您是否需要为左右字符串分配新对象?
  • do you need to reverse the string? 您需要反转字符串吗?

The checking can be done in a very simple loop: 可以在一个非常简单的循环中完成检查:

var len=string.length;
for (int i=0; i<(len/2); i++) {
  if (string[i] != string[len-i-1]) {
    alert(string + " is not a palindrome.");
    return;
  }
}
alert(string + " is a palindrome.");

To ignore spaces and non-alpha numeric characters, it can be re-written as follows: 要忽略空格和非字母数字字符,可以按以下方式重写它:

function isAlphaNumeric( chr ) {
  return ( ((c >= 'a') && (c <= 'z')) ||
           ((c >= 'A') && (c <= 'Z')) ||
           ((c >= '0') && (c <= '9')) );
}

// Note - template taken from @Matt's answer!
function isPalindrome( string ) {
  var i = 0, j = s.length-1;
  while( i < j ) {
    if (isAlphaNumeric(string[i])) {
      if (isAlphaNumeric(string[j])) {
        if ( string[i++].toLowerCase() != string[j--].toLowerCase() ) 
          return false;
      } else {
        j--;
      }
    } else {
      i++;
      if (!isAlphaNumeric(string[j])) j--;
    }
  }
  return true;
}

unreadable + unmaintainable + terse + efficient + recursive + non-branching 难以理解+难以维护+简洁+高效+递归+非分支

function isPalindrome(s,i) {
 return (i=i||0)<0|| i>=s.length/2|| s[i]==s[s.length-1-i]&& isPalindrome(s,++i);
}

Fiddle: http://jsfiddle.net/namcx0yf/ 小提琴: http//jsfiddle.net/namcx0yf/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Java中通过字符串的最有效方式是什么? - What is the most efficient way to go through string's chars in Javascript? 在JavaScript中,将标签转换为链接的最有效方法是什么? - In javascript, what's the most efficient way to I turn tags into links? 比较 javascript 中的 2 个元素的最有效方法是什么? - What's the most efficient way to compare 2 elements in javascript? 在Javascript中创建嵌套div的最有效方法是什么? - What is the most efficient way to create nested div's in Javascript? 在 JavaScript 中处理显示对话框/模式的最有效方法是什么? - What's the most efficient way to handle displaying a dialog/modal in JavaScript? 等待Java中异步函数调用的最有效方法是什么? - What's the most efficient way to wait for an asynchronous function call in Javascript? 使用javascript径向排列图像的最有效方法是什么? - What is the most efficient way to arrange images radially using javascript? 使用JavaScript设置多个弹出窗口的最有效方法是什么? - What is the most efficient way to setup multiple popups using JavaScript? 使用 javascript 呈现字符串模板的最有效方法 - Most efficient way for rendering string templates using javascript 没有“ eval”的情况下评估JavaScript代码字符串的最简单方法是什么? - What's the simplest way to evaluate a string of JavaScript code without 'eval'?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM