Javascript Palindrome Logic

五迷三道 提交于 2019-12-24 04:42:07

问题


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

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

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


回答1:


k = str.length-1;

should be

k = strSqueezed.length-1;

Thats it.

https://jsfiddle.net/aejmjsqk/



来源:https://stackoverflow.com/questions/29288486/javascript-palindrome-logic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!