Valid Palindrome

Valid Palindrome

LeetCode 125

What is Palindrome?

A palindrome is a string or a number read the same backward or forward.

Ex: 101, 1331, 11, PEEP, ROTATOR, etc are some examples of a palindrome

Note - One can make a string palindrome by pasting the reversed version of the original string at the end of the string

Ex: Code is not a palindrome but Codeedoc is a palindrome.

Scenario

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

// Input Format

Input string1 = 'A man, a plan, a canal: Panama'
Input string2 = 'Race a car'
// Output Format

Output1 = true
Output2 = false

Solution

const isValidPalindrome = (str)=>{

    str = str.toLowerCase(); // removing case barrier
    let newStr =''
    let pattern = /[a-z0-9]/g; // only Alphabet and Numbers 

    for(let val of str){
        if (val.match(pattern)){
        // forming a new string free of alphanumeric characters and space
            newStr +=val 
        }
    }
    const reversed = newStr.split('').reverse().join('') // reversing string
    let result = false

    if(reversed===newStr)
        result = true

        return result // returing output
}

let str = 'A man, a plan, a canal: Panama'

console.log(isValidPalindrome(str))

Reference

It is a leet code problem number 125 and it is considered one of the most straightforward problems.