回文检查器未捕获 'almostomla'

Palindrome Checker does not catch 'almostomla'

我写回文检查器。它适用于除“almostomla”之外的所有测试用例场景,我不知道为什么。

我的代码:

function palindrome(str) {
  //deleting all non-alphanumeric characters from the array and changing all the remaining characters to lowercases
  str = str.replace(/[_\W]+/g, "").toLowerCase();

  const a = str.split('');
  console.log(a);
  const b = [...a].reverse().join('');
  console.log(b);
  const c = [...a].join('');
  console.log(c);

  for(var i=0; i<b.length; i++){
    if(b[i] !== c[i]){
      return false;
    } else {
      return true;
    }
  }
}

console.log(palindrome("almostomla"));

for(var i=0; i<b.length; i++){
  if(b[i] !== c[i]){
    return false;
  } else {
    return true;
  }
}

这里的for循环将比较第一个字符,然后return。它不会看第二个字符。您需要设置循环,以便它不断遍历整个单词。如果你愿意,它可以在知道它不是回文后退出

例如:

for(var i=0; i<b.length; i++){
  if(b[i] !== c[i]){
    return false;
  }
}

return true;

正如 evolutionxbox 提到的,还有一个更简单的选项:您可以比较整个字符串,而不是一次比较一个字符。如果两个字符串具有相同的字符,它们将通过 === 检查:

function palindrome(str) {
  //deleting all non-alphanumeric characters from the array and changing all the remaining characters to lowercases
  str = str.replace(/[_\W]+/g, "").toLowerCase();

  const a = str.split('');
  const b = [...a].reverse().join('');
  const c = [...a].join('');

  return b === c;
}

console.log(palindrome("almostomla"));
console.log(palindrome("aha"));

正如其他人告诉你的,你写的字不是回文

根据定义,回文读起来和读起来一样,比如madam

你写

almostomla This is not a palindrome

这应该写成

almotstomla to be a palindrome

编写回文检查器的最简单方法可能是将其拆分为一个数组,然后将其反转。然后,您可以将它连接回一个数组并使用原始值检查它,如下所示:

Code Below:

text == text.split('').reverse().join('');

如果数字是回文,这将 return 为真。

即使 'almostomla' return 也被认为不是上述代码的回文