Palindrome Checker Algorithm

Please review my Palindrome Checker algorithm and offer your feedback. Thank you in advance.

Find the code on Github or below:

 * 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 into the same case (lower or upper 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.
function palindrome(str) {
    str = str.toLowerCase();
    let alphaNumericStr = "";
    let strSpelledBack = "";
    for (let i = 0; i < str.length; i++) {
        if (str[i].match(/[a-zA-Z0-9]/)) {
            alphaNumericStr = alphaNumericStr + str[i];
            strSpelledBack = str[i] + strSpelledBack;
    return alphaNumericStr === strSpelledBack;

There are several ways to solve this one. Your solution works, that’s the most important thing. The first thing you do is convert str to all lower case so you could lose the A-Z in the regex because there will never be upper case letters. You could make this a little more concise using a functional approach, which might also make it a little more obvious what the function is doing just by looking at the code. The nerd in me might wonder if doing a regex match on every character in the string would be much slower than doing a single regex replace at the beginning to get rid of all the non-counting characters. I’m sure it makes no difference on the small inputs the test is using but on very large inputs it might?

These are just some thoughts. Not dissing your solution. Good job solving it.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.