题目
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
示例 1:
输入: "A man, a plan, a canal: Panama"
输出: true
示例 2:
输入: "race a car"
输出: false
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/valid-palindrome 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
知识点
charCodeAt()
charCodeAt() 方法可返回指定位置的字符的 Unicode 编码。这个返回值是 0 - 65535 之间的整数。
charAt()
方法 charCodeAt() 与 charAt() 方法执行的操作相似,只不过前者返回的是位于指定位置的字符的编码,而后者返回的是字符子串。
'a'.charCodeAt(); //97
'b'.charCodeAt(); //98
...
'z'.charCodeAt(); //122 (97+26-1=122)
'A'.charCodeAt(); //65
'B'.charCodeAt(); //66
...
'Z'.charCodeAt(); //90 (65+26-1=90)
'0'.charCodeAt(); //48
'1'.charCodeAt(); //49
'9'.charCodeAt(); //57 (48+10-1=57)
JS实现
/**
* @param {string} s
* @return {boolean}
*/
var isPalindrome = (str) => {
// 字符串转为小写
str = str.toLowerCase();
let temp = "";
// 遍历字符串,过滤其他字符,只保留字母和数字
for (let c of str) {
if (
(c.charCodeAt() >= 48 && c.charCodeAt() <= 57) ||
(c.charCodeAt() >= 97 && c.charCodeAt() <= 122)
) {
temp += c;
}
}
//定义两个指针
let left = 0,
right = temp.length - 1;
while (left < right) {
if (temp[left] != temp[right]) {
return false;
}
left++;
right--;
}
return true;
};