DEV Community

Naya Willis
Naya Willis

Posted on • Updated on

IsPalindrome Code Challenge

Hello, everyone. Today I will be walking you through the isPalindrome problem on LeetCode. Your approach may be different, or perhaps even better but don't rub it in, just enjoy. Ok, so let's do this.

The Task

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

const isPalindrome = s => {
    // CODE GOES IN HERE
};

My Approach

I started by first converting the passed in string to lowercase letters to avoid any case sensitivity issues.

s = s.toLowerCase()

Next, I created a string containing letters a-z and number 0-9 to rule out any special characters i.e !?:.

let alphas = "abcdefghijklmnopqrstuvwxyz0123456789"

Next, I created a variable called caughtAlphas which I'm going to use to push all of the alphas into that array, meanwhile ignoring special characters.

let caughtAlphas = []

Then I declared 2 let variables, one that I'll use to convert the caughtAlphas array to a string, and the second one will give me a boolean value based on whether or not the string is a palindrome

let caughtAlphasToString;
let checkIfPalindrome;

To handle the checking of each character in the string, I used a for loop like so...

for (let i = 0; i < s.length; i++) {
     if(alphas.includes(s[i])) { //alphas contain current char?
          caughtAlphas.push(s[i]) //great, so push it in caught alphas
     }
}

Now, to convert the caughtAlphas array into a string...

caughtAlphasToString = caughtAlphas.join('')

Now, checking it against itself reversed then assign it to the checkIfPalindrome variable

checkIfPalindrome = (caughtAlphasToString === caughtAlphasToString.split('').reverse().join(''))

Lastly, returning it

return checkIfPalindrome

So, now if we put it all together we have...

const isPalindrome = s => {
    s = s.toLowerCase()
    let alphas = "abcdefghijklmnopqrstuvwxyz0123456789"
    let caughtAlphas = []
    let caughtAlphasToString;
    let checkIfPalindrome;

    for (let i = 0; i < s.length; i++) {
        if(alphas.includes(s[i])) {
            caughtAlphas.push(s[i])
        }
    }

    caughtAlphasToString = caughtAlphas.join('')
    checkIfPalindrome = (caughtAlphasToString === caughtAlphasToString.split('').reverse().join(''))
    return checkIfPalindrome
}

This challenge was fun. Hope you enjoyed the breakdown. Post your solutions in the comment section.

Discussion (0)