feat: 双指针125,392
This commit is contained in:
parent
17aed86c56
commit
07a3353880
60
top-interview-leetcode150/double-point/125验证回文字符串.js
Normal file
60
top-interview-leetcode150/double-point/125验证回文字符串.js
Normal file
@ -0,0 +1,60 @@
|
||||
/**
|
||||
* 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
|
||||
}
|
39
top-interview-leetcode150/double-point/392判断子序列.js
Normal file
39
top-interview-leetcode150/double-point/392判断子序列.js
Normal file
@ -0,0 +1,39 @@
|
||||
/**
|
||||
* https://leetcode.cn/problems/valid-palindrome/description/?envType=study-plan-v2&envId=top-interview-150
|
||||
* @param {string} s
|
||||
* @param {string} t
|
||||
* @return {boolean}
|
||||
*/
|
||||
const isSubsequence = function (s, t) {
|
||||
|
||||
};
|
||||
|
||||
/*
|
||||
直接遍历,直接遍历t 检查当前s的第一个字符是否在遍历的过程中找到了,如果找到了,就指向s的第二个字符,继续找,找到全部找到 返回true
|
||||
*/
|
||||
function f1(s, t) {
|
||||
if (s === t) return true;
|
||||
let i = 0; // 指向s中要查找的字符
|
||||
for (const char of t) {
|
||||
if (char === s[i]) i++;
|
||||
if (i === s.length) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/*
|
||||
利用传统for提高效率
|
||||
*/
|
||||
function f2(s, t) {
|
||||
if (s === t) return true;
|
||||
let i = 0; // 指向s中要查找的字符
|
||||
let j = 0; // 指向t中当前遍历的字符
|
||||
for(let j = 0;j<t.length,t++) {
|
||||
|
||||
}
|
||||
for (const char of t) {
|
||||
if (char === s[i]) i++;
|
||||
if (i === s.length) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user