Hi, i have problem with palindrome

can you guys take a look

function palindrome(str) {

  str.toLowerCase();
  var arr = str.split(" ");
  var newStr = arr.join("");
  for(var i = 0; i < newStr.length / 2; i ++){
    if(newStr[i] !== newStr[newStr.length - i])
      return false;
  }
  return true;
}

palindrome(“eye”);

These two lines split the string into an array wherever there is a space (so split it into ‘words’) then join it back up into a string. They don’t really do anything else…

You are missing the reversing step. Which is what I would do after splitting the string.

Unless you are using this to do the comparison… newStr[i] !== newStr[newStr.length - i]

… but I would just compare the array after I split it, rather than merge it again.

But anyway… those two lines above don’t really add value as they are, without doing something first in between them (maybe the first one removes spaces at most?)

Edit:

looked over the solution and noticed in the question write-up:

Note
You’ll need to remove all non-alphanumeric characters (punctuation, spaces and symbols) and turn everything lower case in order to check for palindromes.

Pseudo-code-ish write-up: I used a ‘replace’ and regex to get rid of any spaces and non-alphanumeric characters. Then I split, reversed and joined in one line (make sure you split by letter and not by ‘space’ which breaks it into words) to create a new string… then just compared the two strings without iterating across each one (they should just match).

thank you for the solution. i’m writing it again

1 Like