Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.6k views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...