LeetCode 数据结构入门 day 9 - 栈 / 队列

125 阅读2分钟

这是我参与2022首次更文挑战的第9天,活动详情查看:2022首次更文挑战

有效的括号

原题地址

题目

给定一个只包括 '('')''{''}''['']' 的字符串 s ,判断字符串是否有效。

有效字符串需满足:

  1. 左括号必须用相同类型的右括号闭合。
  2. 左括号必须以正确的顺序闭合。

示例 1:

输入:s = "()"
输出:true

示例 2:

输入:s = "()[]{}"
输出:true

示例 3:

输入:s = "(]"
输出:false

示例 4:

输入:s = "([)]"
输出:false

示例 5:

输入:s = "{[]}"
输出:true

方法

思路:

  1. 定义一个左右括号对应的 map
  2. 循环 s,若是 mapkey,则将 key 存入 栈stack 中,若不是,则比对 s[i] 与栈顶是否一致,不一致则为 false
  3. 循环结束后,若 长度为0,则证明括号都匹配完成,若不为0,则不是有效的括号。

代码:

/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function(s) {
    const map = {
        '(': ')',
        '[': ']',
        '{': '}'
    }
    const stack = []
    for(let i=0; i<s.length; i++) {
        if(map[s[i]]) {
            stack.push(s[i])
        } else if(s[i] !== map[stack.pop()]) {
            return false
        }
    }
    return stack.length === 0
};

结果:

  • 执行结果: 通过
  • 执行用时:64 ms, 在所有 JavaScript 提交中击败了88.13%的用户
  • 内存消耗:41.2 MB, 在所有 JavaScript 提交中击败了22.23%的用户
  • 通过测试用例:91 / 91

用栈实现队列

原题地址

题目

请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(pushpoppeekempty):

实现 MyQueue 类:

  • void push(int x) 将元素 x 推到队列的末尾
  • int pop() 从队列的开头移除并返回元素
  • int peek() 返回队列开头的元素
  • boolean empty() 如果队列为空,返回 true ;否则,返回 false 说明:

只能 使用标准的栈操作 —— 也就是只有 push to toppeek/pop from topsize, 和 is empty 操作是合法的。

你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。  

示例 1:

输入:
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 1, 1, false]

解释:
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false

方法一

代码:

var MyQueue = function() {
    this.stack1 = []
    this.stack2 = []
};

/** 
 * @param {number} x
 * @return {void}
 */
MyQueue.prototype.push = function(x) {
    this.stack1.push(x)
};

/**
 * @return {number}
 */
MyQueue.prototype.pop = function() {
    if(this.stack1.length > 0) {
        return this.stack1.splice(0, 1)
    } else {
        return this.stack2.splice(0, 1)
    }
};

/**
 * @return {number}
 */
MyQueue.prototype.peek = function() {
    return this.stack1[0] || this.stack2[0]
}

/**
 * @return {boolean}
 */
MyQueue.prototype.empty = function() {
    return this.stack1.length === 0 && this.stack2.length === 0
};

/**
 * 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()
 */

结果:

  • 执行结果: 通过
  • 执行用时:44 ms, 在所有 JavaScript 提交中击败了99.94%的用户
  • 内存消耗:41.3 MB, 在所有 JavaScript 提交中击败了5.12%的用户
  • 通过测试用例:22 / 22

方法二

代码:

var MyQueue = function() {
    this.stack1 = []
    this.stack2 = []
};

/** 
 * @param {number} x
 * @return {void}
 */
MyQueue.prototype.push = function(x) {
    this.stack1.push(x)
};

/**
 * @return {number}
 */
MyQueue.prototype.pop = function() {
    if(this.stack2.length === 0) {
        while(this.stack1.length > 0) {
            this.stack2.push(this.stack1.pop())
        }
    } 
    return this.stack2.pop()
};

/**
 * @return {number}
 */
MyQueue.prototype.peek = function() {
    if(this.stack2.length === 0) {
        while(this.stack1.length > 0) {
            this.stack2.push(this.stack1.pop())
        }
    }
    return this.stack2[this.stack2.length-1]
};

/**
 * @return {boolean}
 */
MyQueue.prototype.empty = function() {
    return this.stack1.length === 0 && this.stack2.length === 0
};

/**
 * 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()
 */

结果:

  • 执行结果: 通过
  • 执行用时:60 ms, 在所有 JavaScript 提交中击败了88.58%的用户
  • 内存消耗:41 MB, 在所有 JavaScript 提交中击败了13.56%的用户
  • 通过测试用例:22 / 22

— END