61 lines
1.7 KiB
JavaScript
61 lines
1.7 KiB
JavaScript
/**
|
||
* https://leetcode.cn/problems/valid-palindrome/?envType=study-plan-v2&envId=top-interview-150
|
||
* @param {string} s
|
||
* @return {boolean}
|
||
*/
|
||
const isPalindrome = function (s) {
|
||
|
||
};
|
||
|
||
/*
|
||
把符合要求的字符存入数组中,之后判断反转的数组和原数组是否一致,如果一致就是回文
|
||
*/
|
||
function f1(s) {
|
||
// 创建一个新的数组,用来存储有效字符(字母和数字)
|
||
const filteredChars = [];
|
||
|
||
// 遍历原字符串,将符合要求的字符存入新数组并转为小写
|
||
for (let i = 0; i < s.length; i++) {
|
||
const char = s[i];
|
||
if (/[a-zA-Z0-9]/.test(char)) {
|
||
filteredChars.push(char.toLowerCase());
|
||
}
|
||
}
|
||
|
||
// 将新数组转换为字符串,并与反转后的字符串比较
|
||
const reversedStr = filteredChars.slice().reverse().join('');
|
||
return filteredChars.join('') === reversedStr;
|
||
}
|
||
|
||
/*
|
||
利用双指针来判断是否符合要求,首先创建左右两个指针,判断当前字符是不是有效字符,如果不是就跳过,然后比较s[left] 和 s[right]
|
||
如果不相等直接返回false,如果循环遍历完毕都没问题,那么就是一个回文字符串,
|
||
思考:奇偶会影响判断吗?
|
||
*/
|
||
function f2(s) {
|
||
let left = 0;
|
||
let right = s.length - 1;
|
||
|
||
while (left < right) {
|
||
// 跳过非字母数字字符
|
||
if (!(/[a-zA-Z0-9]/.test(s[left]))) {
|
||
left++;
|
||
continue;
|
||
}
|
||
if (!(/[a-zA-Z0-9]/.test(s[right]))) {
|
||
right--;
|
||
continue;
|
||
}
|
||
|
||
// 比较字符是否相等,忽略大小写
|
||
if (s[left].toLowerCase() !== s[right].toLowerCase()) {
|
||
return false; // 如果不相等,返回false
|
||
}
|
||
|
||
left++;
|
||
right--;
|
||
}
|
||
|
||
return true; // 如果完全匹配,返回true
|
||
}
|