125. Valid Palindrome

Leetcode

https://leetcode.com/problems/valid-palindrome/

題目

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.

解答

  • 方法一

var isPalindrome = function(s) {
    const str = s.replace(/[^A-Za-z0-9]/g, '').toLowerCase();
    for(let i=0; i<str.length/2; i++) {
      if(str[i] !== str[str.length - 1 - i]) return false;
    }
    return true;
};

Runtime: 113 ms, faster than 26.22% of JavaScript online submissions for Valid Palindrome.

Memory Usage: 40.7 MB, less than 91.95% of JavaScript online submissions for Valid Palindrome.

測資

let s = "A man, a plan, a canal: Panama"; // true
s = "race a car"; // false
s = " "; // true
s = "ab_a"; // true

console.log(isPalindrome(s))

Last updated

Was this helpful?