Skip to content

Latest commit

 

History

History
75 lines (55 loc) · 1.46 KB

125.Valid Palindrome.md

File metadata and controls

75 lines (55 loc) · 1.46 KB

125.Valid Palindrome

Easy

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

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"
Output: true

Example 2:

Input: "race a car"
Output: false

这是一道考察回文的题目,而且是最简单的形式,即判断一个字符串是否是回文。

思路是头尾两个指针往中间对比,不过判断字符和数字的是从别处拿来用的。。

/**
 * @param {string} s
 * @return {boolean}
 */
var isPalindrome = function(s) {
    //转为小写
    s = s.toLowerCase();
    let left = 0
    let right = s.length - 1
    
    while (left < right) {
        if (!isValid(s[left])) {
          left++;
          continue;
        }
        if (!isValid(s[right])) {
          right--;
          continue;
        }
        if (s[left] === s[right]) {
          left++;
          right--;
        } else {
          break;
        }
    }
    return right <= left;
};

//判断是否是合法字符(只处理数字与字符)
function isValid(c) {
  const charCode = c.charCodeAt(0);
  const isDigit =
    charCode >= "0".charCodeAt(0) && charCode <= "9".charCodeAt(0);
  const isChar = charCode >= "a".charCodeAt(0) && charCode <= "z".charCodeAt(0);

  return isDigit || isChar;
}