本文介绍了JavaScript回文逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经检查了该线程:使用Javascript进行回文检查但是,我看上去更加修复我自己的算法.我现在只是在线编程,因此我无法访问一个好的调试器.因此,发现的任何提示/调试问题将不胜感激.这是代码:

I have checked this thread: Palindrome check in Javascript But I'm more so looking to fix my own algorithm. I am just programming online right now so I do not have access to a good debugger. So any hints/debugging problems found would be greatly appreciated. Here's the code:

function isPalindrome(str) {
if(str !== null && str !== undefined && str !== NaN) {
 var strStripped = str.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()@]/g,"");
 var strSqueezed = strStripped.replace(/ /g, "");
 var i, k;
 k = str.length-1;
 var numOfValidComparisons = 0;
  for(i=0; i<strSqueezed.length; i++) {
   if(strSqueezed.charAt(i) === strSqueezed.charAt(k)) {
     numOfValidComparisons++;
   }
   k--;
  }
 if(numOfValidComparisons === strSqueezed.length)
   return true;
 else
   return false;
   }
  return false;
}

我在纸上写下了循环比较逻辑,一时感到困惑.如果您不熟悉这里的回文式: http://en.wikipedia.org/wiki/回文

I've written down the loop comparison logic on paper and have been baffled momentarily. If you're unfamiliar with what a palindrome is here: http://en.wikipedia.org/wiki/Palindrome

我现在正在使用的测试是此字符串"race car"(在纸上看起来很棒)

The test I'm working with right now is this string "race car" (and looks great on paper)

推荐答案

k = str.length-1;

应该是

k = strSqueezed.length-1;

就这样.

https://jsfiddle.net/aejmjsqk/

这篇关于JavaScript回文逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 11:29