基础数据结构与算法题(日常)
kingcwt2022-09-28前端算法 基础数据结构
栈相关
- 栈:后进先出
push入栈,pop出栈
20.有效的括号
- 时间: 2022-09-28
- 地址: https://leetcode.cn/problems/valid-parentheses/
/**
* 20.有效的括号
* @param {string} s
* @return {boolean}
*/
var isValid = function (s) {
let stack = [];
for (let i = 0; i < s.length; i++) {
let item = s[i];
if (item === "(" || item === "{" || item === "[") {
stack.push(item);
} else {
let current = stack[stack.length - 1];
if (
(item === ")" && current === "(") ||
(item === "}" && current === "{") ||
(item === "]" && current === "[")
) {
stack.pop();
} else {
return false;
}
}
}
return stack.length === 0;
};
console.log(isValid("(){}"));
console.log(isValid("()[}"));
1047.删除字符串中的所有相邻重复
/**
* 删除字符串中的所有相邻重复
* @param {string} s
* @return {string}
*/
var removeDuplicates = function (s) {
let stack = [];
for (let i = 0; i < s.length; i++) {
let start = s[i];
if (stack.length > 0) {
if (start === stack[stack.length - 1]) {
stack.pop();
} else {
stack.push(start);
}
} else {
stack.push(start);
}
}
return stack.join("");
};
71.简化路径
- 时间:2022-11-23
- 地址:https://leetcode.cn/problems/simplify-path/description/
/**
* 简化路径
* @param {string} path
* @return {string}
*/
var simplifyPath = function (path) {
let stack = [];
let arr = path.split("/");
arr.forEach((item) => {
if (item === "..") {
stack.pop();
} else if (item && item !== ".") {
stack.push(item);
}
});
return stack.length ? (str = "/" + stack.join("/")) : "/";
};
933.最近的请求次数
- 时间:2022-11-28
- 地址:https://leetcode.cn/problems/number-of-recent-calls/description/
var RecentCounter = function () {
this.queue = [];
};
/**
* @param {number} t
* @return {number}
*/
RecentCounter.prototype.ping = function (t) {
this.queue.push(t);
while (this.queue[0] < t - 3000) {
this.queue.shift();
}
return this.queue.length;
};
141.环形链表
- 时间:2022-11-28
- 地址:https://leetcode.cn/problems/number-of-recent-calls/description/
let a = { key: "3" };
let b = { key: "2" };
let c = { key: "0" };
let d = { key: "-4" };
a.next = b;
b.next = c;
c.next = d;
d.next = b;
var hasCycle = function (head) {
let a = head,
b = head;
while (a !== null && a.next !== null) {
b = b.next;
a = a.next.next;
if (a === b) return true;
}
return false;
};
console.log(hasCycle(a));
237.删除链表中的节点
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} node
* @return {void} Do not return anything, modify node in-place instead.
*/
var deleteNode = function (node) {
node.val = node.next.val;
node.next = node.next.next;
};
83. 删除排序链表中的重复元素
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var deleteDuplicates = function (head) {
if (!head) {
return head;
}
let cur = head;
while (cur.next) {
if (cur.val == cur.next.val) {
cur.next = cur.next.next;
} else {
cur = cur.next;
}
}
return head;
};