zoukankan      html  css  js  c++  java
  • Leetcode** 20. Valid Parentheses

    Description: Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

    An input string is valid if:

    1. Open brackets must be closed by the same type of brackets.
    2. Open brackets must be closed in the correct order.

    Link: 20. Valid Parentheses

    Examples:

    Example 1:
    Input: s = "()"
    Output: true
    
    Example 2:
    Input: s = "()[]{}"
    Output: true
    
    Example 3:
    Input: s = "(]"
    Output: false
    
    Example 4:
    Input: s = "([)]"
    Output: false
    
    Example 5:
    Input: s = "{[]}"
    Output: true

    思路: 用先进先出的栈来做,遍历s时,当是左半边的括号时,就放入栈中,当是右半边的括号时,就弹出栈顶的元素,只能当当前遍历到的和栈顶的括号匹配时,才说明其顺序是对的,否则return False,直到遍历完所有的元素,如果stack不为空,说明有没有被匹配的左半边, return False.

    class Solution(object):
        def isValid(self, s):
            """
            :type s: str
            :rtype: bool
            """
            stack = []
            for c in s:
                if c in ['(', '[', '{']:
                    stack.append(c)
                else:
                    if not stack: return False
                    top = stack.pop()
                    if top == '(' and c != ')' or 
                       top == '[' and c != ']' or 
                       top == '{' and c != '}': return False
            return not stack

    日期: 2021-04-17

  • 相关阅读:
    OO第三单元总结
    OO第二单元总结
    OO第一单元总结
    OO第四单元总结
    OO第三单元总结
    OO第二单元总结
    OO第一单元总结
    BUAA_OO_2020_Total_Summary
    BUAA_OO_2020_Unit3_Summary
    BUAA_OO_2020_Unit2_Summary
  • 原文地址:https://www.cnblogs.com/wangyuxia/p/14672123.html
Copyright © 2011-2022 走看看