LeetCode 堆栈队列 —— 括号匹配(20、232、155)

1. 堆栈(stack)

  • 20,20. Valid Parentheses,括号匹配,堆栈(python 中使用 list 即可实现表示堆栈,list.append:入栈,list.pop():出栈)实现:

    • 左括号((、[、{)入栈;
    • 右括号()、]、})出栈;
    • 遍历全部字符串后,堆栈为空;
    class Solution(object):
        def isValid(self, s):
            """
            :type s: str
            :rtype: bool
            """
            stack = []
            para_map = {')':'(', ']':'[', '}':'{'}
            for c in s:
                if c not in para_map:
                    stack.append(c)
                elif not stack or stack.pop() != para_map.get(c):
                    return False
            return not stack
    
  • 155,155. Min Stack,

    • 实现思路:使用两个栈进行实现,一个是常规的栈(dataStack),一个用来存放截止到每一步的最小值(minStack);
    • push:minStack 为空,或压入的值<=minStack.peek(),则执行压入;
    • pop:dataStack 弹出的值(不可能小于 minStack.peek()) == minStack.peek(),则 minStack 也进行弹出
    class MinStack {
        
        private Stack dataStack;
        private Stack minStack;
        
        /** initialize your data structure here. */
        public MinStack() {
            dataStack = new Stack<>();
            minStack = new Stack<>();
        }
        
        public void push(int x) {
            dataStack.push(x);
            if (minStack.isEmpty() || x <= minStack.peek()) {
                minStack.push(x);
            }
        }
        
        public void pop() {
            if (dataStack.isEmpty()) {
                throw new RuntimeException("Stack is empty!");
            }
            Integer retValue = dataStack.pop();
            if (retValue.equals(minStack.peek())) {
                minStack.pop();
            }        
        }
    }
    

2. 用栈实现队列

232. Implement Queue using Stacks

通过栈实现队列,需要两个栈,一个输入栈(输入栈仅用来输入,push),一个输出栈(仅用来输出,pop和peek):

class MyQueue(object):

    def __init__(self):
        self.input_stack = []
        self.output_stack = []
        

    def push(self, x):
        self.input_stack.append(x)
        			# 仅用来输入

    def pop(self):
        if not self.output_stack:
            while self.input_stack:
                self.output_stack.append(self.input_stack.pop())
        return self.output_stack.pop()
        		# 仅用来输出

    def peek(self):
        if not self.output_stack:
            while self.input_stack:
                self.output_stack.append(self.input_stack.pop())
        return self.output_stack[-1]
        		# 仅用来输出

    def empty(self):
        return not self.input_stack and not self.output_stack

你可能感兴趣的:(面试,leetcode)