How/Best way to check the string is Palindrome or not in Javascript


What is palindrome

Palindrome is a word, phrase, or sequence that reads the same backwards as forwards as shown in the below example.

palindrome example

Example 1 palindrome using reverse function

var profile = 'madam';
if (profile == profile.split('').reverse().join(''))
    console.log(profile + " is a palindrome");
else
    console.log(profile + " is not a palindrome");

Using reverse is overkill because you don’t need to generate an extra string, you just need to query the existing one. The following example checks the first and last characters are the same, and then walks further inside the string checking the results each time. It returns as soon as s is not a palindrome.

The problem with the reverse approach is that it does all the work up front. It performs an expensive action on a string, then checks character by character until the strings are not equal and only then returns false if it is not a palindrome. If you are just comparing small strings all the time then this is fine, but if you want to defend yourself against bigger input then you should consider this algorithm.

Example 2 palindrome without using reverse

var profile = 'madam';

function isPalindrome(profile) {
    var n = profile.length;
    for (var i = 0; i < (n / 2) ; ++i) {
        if (profile.charAt(i) != profile.charAt(n – i – 1))
            return false;
    }
    return true;
}

var isit = isPalindrome(profile);
if(isit)
    console.log(profile + " is a palindrome");
else
    console.log(profile + " is not a palindrome");

Happy coding

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s