Valid Parentheses

发布时间 2023-06-13 13:39:08作者: Artwalker

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

An input string is valid if:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Every close bracket has a corresponding open bracket of the same type.

Example 1:

Input: s = "()"
Output: true

Example 2:

Input: s = "()[]{}"
Output: true

Example 3:

Input: s = "(]"
Output: false

Solution:

class Solution(object):
    def isValid(self, s):  
        stack = []  
        mapping = {')': '(', '}': '{', ']': '['}  
        for char in s:  
            if char in mapping:  # 判断char是否为字典mapping的键
                # 这种处理方式可以避免在栈为空时尝试弹出元素而引发的异常
                top = stack.pop() if stack else '#'  
                if mapping[char] != top:  
                    return False  
            else:  
                stack.append(char)  
        return not stack