Python3 effective parentheses issue

Python3 effective parentheses issue

Original title https://leetcode-cn.com/problems/valid-parentheses/

Includes only a given '(', ')' string, '{', '}', '[', ']', and determine whether the string is valid.

Valid string must meet:

Left bracket must be closed by a closing parenthesis of the same type.
Left parenthesis must be closed in the correct order.
Note the empty string can be considered a valid string.

Example 1:

输入: "()"
输出: true

Example 2:

输入: "()[]{}"
输出: true

Example 3:

输入: "(]"
输出: false

Example 4:

输入: "([)]"
输出: false

Example 5:

输入: "{[]}"
输出: true

Problem solving:

class Solution:
    def isValid(self, s: str) -> bool:
        stack = [] # 只存未被配对的( [ {   遇到配对的直接出栈
        n = len(s)
        for i in range(n):
            w = s[i]
            if w == ')':
                length = len(stack)
                if length == 0 or stack[length - 1] != '(':
                    return False
                else:
                    stack.pop()
            elif w == '}':
                length = len(stack)
                if length == 0 or stack[length - 1] != '{':
                    return False
                else:
                    stack.pop()
            elif w == ']':
                length = len(stack)
                if length == 0 or stack[length - 1] != '[':
                    return False
                else:
                    stack.pop()
            elif w == '(' or w == '{' or w == '[':
                stack.append(w)
        return len(stack) == 0 # 都配对了则栈为空  如果栈不为空则说明未配对
Published 24 original articles · won praise 0 · Views 416

Guess you like

Origin blog.csdn.net/qq_18138105/article/details/105167805