LeetCode 125 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.
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.
Example 3:
Input: s = " "
Output: true
Explanation: s is an empty string "" after removing non-alphanumeric characters.
Since an empty string reads the same forward and backward, it is a palindrome.
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/valid-palindrome
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解
/**
* 忽略大小写
* 空字符串默认为true
* 首先正则去掉非字母和数字的字符
* 然后双指针从两端开始遍历,只要有一个不相等就返回false
* @param {string} s
* @return {boolean}
*/
var isPalindrome = function (s) {
const newStr = s.replace(/[^A-Za-z0-9]/g, '')
if (newStr === '') return true
let left = 0, right = newStr.length - 1
while(left < right){
if(newStr[left].toLocaleLowerCase() !== newStr[right].toLocaleLowerCase()){
return false
}
left ++
right --
}
return true
};