Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.0k views
in Technique[技术] by (71.8m points)

javascript - Palindrome Checker does not catch 'almostomla'

I write palindrome checker. It works for all the test case scenarios but "almostomla" and I don't know why.

My code:

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"));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

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

This for loop here is going to compare the first characters, and then return. It won't look at the second characters. You'll need to set up the loop so it keeps going through the entire word. It can bail out once it knows it's not a palindrome if you like

For example:

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

return true;

As evolutionxbox mentions, there's also a simpler option: you can compare the entire strings instead of comparing one character at a time. If two strings have identical characters, they will pass a === check:

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"));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...