Mastering LeetCode for Top-Tier Programming Interviews 125: Valid Palindrome

Cracking the Code : 125. Valid Palindrome

Preview questions

A Phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.

Given a string s, return true if it is a palindrome, or false otherwise.

Example 1:

Input : s = "A man, a plan, a canal:Panama"

Output: true

Explanation: "amanaplanacanalpanama" is a palindrome

Example 2:

Input : s = "race a car"

Output: false

Explanation: "raceacar" is not a palindrome.

Alright let's crack it

Step 1: Verify the constraints

Because this question is very simple, we can ignore if there are any constraints for this question.

Step 2: Write out some test case

test case one: "aabaa" the result will be true

test case two: "aabbaac" the result will be false

test case three: "" the result will be false

There is a lot of approaches to solving this question, but I create my algorithm to solve this:

  1. Create a new string to remove all symbols, and space and set all the strings to lowercase.

  2. Create a new string to compare it to the first strings.

  3. do looping for the first string and count it down the crease to insert the compare string the value from the last index, you can say this operation is reversed strings.

  4. after that you can compare it, it the first string and compare string is same then we return true, if not we return false.

var isPalindrome = function(s) {
    var newString = s.replaceAll(/[^A-Z0-9]/ig,"").toLowerCase()
    var compareString = ""

    for (let i = newString.length-1; i >= 0; i--){
        compareString += newString[i]
    }

    if (newString === compareString) {
        return true;
    } else {
        return false
    }
};

When I submit it I get the result :

Alright, we already fixed it, if you have a better solution. please comment below