zoukankan      html  css  js  c++  java
  • Leetcode python 20. 有效的括号 232. 用栈实现队列

    20. 有效的括号

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

    有效字符串需满足:

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

    示例 1:
    输入:s = "()"
    输出:true

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

    示例 3:
    输入:s = "(]"
    输出:false

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

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

    class Solution:
        def isValid(self, s: str) -> bool:
            if len(s) % 2 == 1:
                return False
            
            pairs = {
                ")": "(",
                "]": "[",
                "}": "{",
            }
            stack = list()
            for ch in s:
                if ch in pairs:
                    if not stack or stack[-1] != pairs[ch]:
                        return False
                    stack.pop()
                else:
                    stack.append(ch)
            return not stack
    

    执行用时:32 ms, 在所有 Python3 提交中击败了75.29%的用户

    内存消耗:15 MB, 在所有 Python3 提交中击败了47.23%的用户

    class Solution:
        def isValid(self, s: str) -> bool:
            dic = {'{': '}',  '[': ']', '(': ')', '?': '?'}
            stack = ['?']
            for c in s:
                if c in dic: stack.append(c)
                elif dic[stack.pop()] != c: return False 
            return len(stack) == 1
    

    执行用时:24 ms, 在所有 Python3 提交中击败了97.93%的用户

    内存消耗:15 MB, 在所有 Python3 提交中击败了47.23%的用户

    232. 用栈实现队列

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

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

    说明:

    • 你只能使用标准的栈操作 —— 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。

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

    进阶:

    • 你能否实现每个操作均摊时间复杂度为 O(1) 的队列?换句话说,执行 n 个操作的总时间复杂度为 O(n) ,即使其中一个操作可能花费较长时间。

    输入:
    ["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

    提示:

    • 1 <= x <= 9
    • 最多调用 100pushpoppeekempty
    • 假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)
    class MyQueue:
        def __init__(self):
            """
            in主要负责push,out主要负责pop
            """
            self.stack_in = []
            self.stack_out = []
        def push(self, x: int) -> None:
            """
            有新元素进来,就往in里面push
            """
            self.stack_in.append(x)
        def pop(self) -> int:
            """
            Removes the element from in front of queue and returns that element.
            """
            if self.empty():
                return None
            
            if self.stack_out:
                return self.stack_out.pop()
            else:
                for i in range(len(self.stack_in)):
                    self.stack_out.append(self.stack_in.pop())
                return self.stack_out.pop()
        def peek(self) -> int:
            """
            Get the front element.
            """
            ans = self.pop()
            self.stack_out.append(ans)
            return ans
        def empty(self) -> bool:
            """
            只要in或者out有元素,说明队列不为空
            """
            return not (self.stack_in or self.stack_out)
    

    执行用时:28 ms, 在所有 Python3 提交中击败了88.53%的用户
    内存消耗:15.2 MB, 在所有 Python3 提交中击败了12.01%的用户

  • 相关阅读:
    电力基本知识
    .net图表工具汇总
    最重要的十年做什么才不浪费?
    花10分钟看一看少走30年弯路
    给明年依然年轻的我们
    Qt经典—线程、事件与Qobject
    C#源码500份
    .NET 性能优化方法总结==转
    qt +ChartDirector 绘制图表
    创业者,你为什么这么着急?
  • 原文地址:https://www.cnblogs.com/hereisdavid/p/15328031.html
Copyright © 2011-2022 走看看