LeetCode 232.用栈实现队列
📖 考察点
栈和队列的理解
📖 题意理解
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):
💡 解题思路
🔑 关键点总结
💻 代码实现
JavaScript
var MyQueue = function() {
this.in = [];
this.out = [];
};
/**
* @param {number} x
* @return {void}
*/
MyQueue.prototype.push = function(x) {
this.in.push(x);
};
/**
* @return {number}
*/
MyQueue.prototype.pop = function() {
let n = this.out.length;
if(n){
return this.out.pop();
}
while(this.in.length){
this.out.push(this.in.pop());
}
return this.out.pop();
};
/**
* @return {number}
*/
MyQueue.prototype.peek = function() {
const x = this.pop();
this.out.push(x);
return x;
};
/**
* @return {boolean}
*/
MyQueue.prototype.empty = function() {
return !this.in.length && !this.out.length
};
/**
* Your MyQueue object will be instantiated and called as such:
* var obj = new MyQueue()
* obj.push(x)
* var param_2 = obj.pop()
* var param_3 = obj.peek()
* var param_4 = obj.empty()
*/
Rust
⏱️ 复杂度分析
📚 总结与反思
LeetCode 225.用队列实现栈
📖 考察点
栈和队列的理解
📖 题意理解
💡 解题思路
💻 代码实现
JavaScript
var MyStack = function() {
this.queue = [];
};
/**
* @param {number} x
* @return {void}
*/
MyStack.prototype.push = function(x) {
this.queue.push(x);
};
/**
* @return {number}
*/
MyStack.prototype.pop = function() {
let n = this.queue.length;
while(n-->1){
this.queue.push(this.queue.shift());
}
return this.queue.shift();
};
/**
* @return {number}
*/
MyStack.prototype.top = function() {
let x;
let n = this.queue.length;
while(n-->0){
let temp = this.queue.shift();
if(n===0){
x = temp;
}
this.queue.push(temp);
}
return x;
};
/**
* @return {boolean}
*/
MyStack.prototype.empty = function() {
return !this.queue.length
};
/**
* Your MyStack object will be instantiated and called as such:
* var obj = new MyStack()
* obj.push(x)
* var param_2 = obj.pop()
* var param_3 = obj.top()
* var param_4 = obj.empty()
*/
Rust
⏱️ 复杂度分析
📚 总结与反思
LeetCode 20.有效的括号
📖 考察点
栈的应用
📖 题意理解
💡 解题思路
思路一:
思路二:
🔑 关键点总结
💻 代码实现
JavaScript
/**
* @param {string} s
* @return {boolean}
*/
var isValid = function(s) {
let dict = ['(',')','{','}','[',']'];
let charList = s.split("");
let stack = [];
for (let char of charList){
let index = dict.findIndex((c)=>c===char);
if(index%2 ===0){
stack.push(char);
}else{
let temp = stack.pop();
if(temp !== dict[index-1]){
return false;
}
}
}
return stack.length === 0;
};
Rust
⏱️ 复杂度分析
📚 总结与反思
⏱️ 复杂度分析
📚 总结与反思
LeetCode 1047,删除字符串中所有相邻的重复项
📖 考察点
栈的应用
📖 题意理解
给出由小写字母组成的字符串 s,重复项删除操作会选择两个相邻且相同的字母,并删除它们。
在 s 上反复执行重复项删除操作,直到无法继续删除。
在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。
💡 解题思路
思路一:
思路二:
🔑 关键点总结
💻 代码实现
JavaScript
/**
* @param {string} s
* @return {string}
*/
var removeDuplicates = function(s) {
let stack = [];
let charList = s.split('');
for(let char of charList){
let top = stack[stack.length-1];
if(top === char){
stack.pop();
}else{
stack.push(char);
}
}
return stack.join('');
};
Rust