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
};
Enter fullscreen mode Exit fullscreen mode

My Approach

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

s = s.toLowerCase()
Enter fullscreen mode Exit fullscreen mode

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

let alphas = "abcdefghijklmnopqrstuvwxyz0123456789"
Enter fullscreen mode Exit fullscreen mode

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 = []
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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
     }
}
Enter fullscreen mode Exit fullscreen mode

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

caughtAlphasToString = caughtAlphas.join('')
Enter fullscreen mode Exit fullscreen mode

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

checkIfPalindrome = (caughtAlphasToString === caughtAlphasToString.split('').reverse().join(''))
Enter fullscreen mode Exit fullscreen mode

Lastly, returning it

return checkIfPalindrome
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)