Question:

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

Note: For the purpose of this problem, we define empty string as valid palindrome.

Example:

  1. Input: "A man, a plan, a canal: Panama"
  2. Output: true
  1. Input: "race a car"
  2. Output: false

Solution:

  1. /**
  2. * @param {string} s
  3. * @return {boolean}
  4. */
  5. var isPalindrome = function(s) {
  6. if(!s)return true;
  7. const regex = /[a-zA-Z0-9]+?/gi;
  8. let str = s.match(regex);
  9. if(!str) return true;
  10. let len = str.length;
  11. if(len === 1) return true;
  12. for (let i = 0; i < Math.floor(len / 2); i++) {
  13. if (str[i].toLowerCase() === str[len-i-1].toLowerCase()) continue;
  14. return false;
  15. }
  16. return true;
  17. };

Runtime: 80 ms, faster than 39.01% of JavaScript online submissions for Valid Palindrome.