Thursday, May 3, 2018

Check palindrome, simplest approach

Check palindrome:

The simplest approach to a quick, and efficient check palindrome program:

We don't need loops for everything!

The internal working is with a couple of if statements.


Always try to condense the program logic to skip loops if possible. There any many ways to implement simple tests which ensure the skipping of loops.


CODE(Javascript):


function checkPalindrome(inputString) {
    if(inputString.length == 1)
        return true;
    if(inputString.length % 2 == 0){
        if(inputString.slice(0, inputString.length / 2) == inputString.slice(inputString.length / 2, inputString.length).split("").reverse().join(""))
            return true;
    }
    else{
        if(inputString.slice(0, inputString.length / 2) == inputString.slice((inputString.length / 2) + 1, inputString.length).split("").reverse().join(""))
            return true;
    }
    
    
    return false;

}

Explanation:

  • String reverse in javascript 
    (ARRAY).split("").reverse().join("")
    

    This snippet can be used to reverse strings in javascript. The split("") splits the string into an array of characters. Next, the reverse() function reverses a JS Array. The join("") function joins them up again.
  • String slice is used to slice the string into smaller chunks. We slice at the center, if the string is of even length, if the string is of odd length, we slice around the center character.
  • If the string is of length 1, we know it’s a palindrome.
  • If the half of the string matches exactly with the other half, then we know it is a palindrome.



That is the logic behind this code! Isn't simple? Do try it out, I am sure it works for all test cases! Until next time!



1 comment:

  1. The solution is case sensitive, so it will not work in case of palindromic names, for example.

    Don't you think that loop is used inside array reverse function? And inside string comparison operator?

    Do you think the described approach is more effective than a single loop?

    ReplyDelete