[英]Can someone please tell me why this method did not work for finding palindromes?
Attempting to complete the algorithms on freeCodeCamp. 尝试完成freeCodeCamp上的算法。 I eventually found an approach that works, but i still don't understand why this method did not work for all cases. 我最终找到了一种可行的方法,但是我仍然不明白为什么这种方法不适用于所有情况。
function palindrome(str) {
var alphaNumericStr = str.replace(/\W/g,"");
var lowerCaseAlphaNumericString = alphaNumericStr.toLowerCase();
var arr = lowerCaseAlphaNumericString.split("");
arr.reverse();
var reversedString = arr.join("");
if(str === reversedString){
return true;
}
return false;
}
palindrome("race car");
You're comparing a string which has been stripped of spaces and converted to lowercase to the original string. 您正在将已删除空格并转换为小写的字符串与原始字符串进行比较。 Replace your conditional with: 将条件替换为:
if(lowerCaseAlphaNumericString == reversedString){
rethrn true;
}
return false;
Here's a little refactor if you're interested: 如果您有兴趣,这里有一些重构:
// ...
var reversedString = arr.join('');
return lowerCaseAlphaNumericString == reversedString;
This is where you are going wrong if(str === reversedString)
if(str === reversedString)
这就是你要出错的地方
Try this: 尝试这个:
if(lowerCaseAlphaNumericString === reversedString) {
return true;
}
return false;
}
There could be another approach. 可能有另一种方法。 In this approach, the corner cases are handled separately. 在这种方法中,将极端情况分开处理。
function check_Palindrome(input_str){
var astr = input_str.toLowerCase().replace(/\W/g,'');
var acount = 0;
if(astr==="") {
console.log("Not Palindrome.");
return false;
}
if ((astr.length) % 2 === 0) {
acount = (astr.length) / 2;
} else {
if (astr.length === 1) {
console.log("Palindrome.");
return true;
} else {
acount = (astr.length - 1) / 2;
}
}
for (var x = 0; x < acount; x++) {
if (astr[x] != astr.slice(-1-x)[0]) {
console.log("Not Palindrome.");
return false;
}
}
console.log("Palindrome.");
return true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.