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

posted @ 2021-04-17 21:07  summer_mimi  阅读(32)  评论(0编辑  收藏  举报