Basic Algorithm Scripting – Check for Palindromes

Basic Algorithm Scripting – Check for Palindromes

Problem Statement (Check for Palindromes) :

Return true if the given string is a palindrome. Otherwise, return false.

A palindrome is a word or sentence that’s spelled the same way both forward and backward, ignoring punctuation, case, and spacing.

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

We’ll pass strings with varying formats, such as "racecar", "RaceCar", and "race CAR" among others.

We’ll also pass strings with special symbols, such as "2A3*3a2", "2A3 3a2", and "2_A3*3#A2".

Here are some helpful links:

 

Solution :

function palindrome(str) {
  
  str = str.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()\s]/gi,"");
  
  str = str.toLowerCase();
  
  var reverse = str.split("").reverse().join("");
  
  if(reverse === str){
    return true;
  }
  else{
    return false;
  }
}

Explanation :

The basic logic behind the palindrome problem is to check if the string provided is exactly equal to its reverse.

But the tricky part in this problem is that they have given some symbols in between the string and we have to scrape the original string out of the without the unwanted things(punctuation, spaces and symbols).

 

We will do this line by line.

  1. str = str.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()\s]/gi,"");– There is some regex action going on here. We are replacing every unwanted thing in the string. That’s how we scraped the actual string.
  2. str = str.toLowerCase(); – Nothing fancy, just lower case the string extracted from that replace string.
  3. reverse = str.split("").reverse().join("");– In (reverse a string) post, I have explained how we can reverse a given string.

Now, we just need to check if the string from step-2 is equal to the reverse variable and we will have our answer.

You can find more problems solved in FreeCodeCamp – Basic Algorithm Scripting – Solved

www.000webhost.com