LeetCode Notes: Valid Palindrome

Question

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

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.

Constraints:

  • 1 <= s.length <= 2 * 105
  • s consists only of printable ASCII characters.

Solution

Analysis:

  1. First remove non-digits and non-letter characters
  2. Loop this new string to determine whether the strings after moving the same distance from the start and end positions are the same. If they are all the same, the result is a palindrome. If any set of strings is different, it is not a palindrome.

Code:

/**
  * @param {string} s
  * @return {boolean}
  */
var isPalindrome = function(s) {

     // Only keep numbers and letters
     const str = s.replace(/[^0-9a-zA-Z]*/g,'').toLowerCase()

     // Loop to half of the position
     for(let i = 0; i <(str.length-1) / 2; i++){

         // Compare the values at the same position before and after, if any pair of values is different, it is not a palindrome array
         if(str[i] !== str[str.length-i-1]){
             return false
         }
     }

     return true
};

Reference

Comments