leetcode刷题-栈

leetcode上关于栈的题目大家可以先做20,155,232,844,224,682,496.

20
给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。



class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        pairs={')':'(','}': '{',']':'['
                }
        stack=list()
        for string in s:
            if string in pairs.keys():
                if not stack or stack[-1]!=pairs[string]:
                    return False
                else :
                    stack.pop()
            else :
                stack.append(string)
        
        if not stack:
            return True
        else :
            return False

155
设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。

push(x) —— 将元素 x 推入栈中。
pop() —— 删除栈顶的元素。
top() —— 获取栈顶元素。
getMin() —— 检索栈中的最小元素。

class MinStack(object):

    def __init__(self):
        self.stack=[]

    def push(self, val):
        """
        :type val: int
        :rtype: None
        """
        return self.stack.append(val)


    def pop(self):
        """
        :rtype: None
        """
        return self.stack.pop()

    def top(self):
        """
        :rtype: int
        """
        return self.stack[-1]

    def getMin(self):
        """
        :rtype: int
        """
        return min(self.stack)

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

你可能感兴趣的:(leetcode刷题-栈)