Python3 tema paréntesis eficaces

Python3 tema paréntesis eficaces

Título original https://leetcode-cn.com/problems/valid-parentheses/

Incluye solo a '(', ')' cadena dada, '{', '}', '[', ']', y determinar si la cadena es válida.

cadena válida debe cumplir:

ménsula izquierda debe ser cerrado por un paréntesis de cierre del mismo tipo.
paréntesis de apertura debe estar cerrada en el orden correcto.
Tenga en cuenta la cadena vacía se puede considerar una cadena válida.

Ejemplo 1:

输入: "()"
输出: true

Ejemplo 2:

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

Ejemplo 3:

输入: "(]"
输出: false

Ejemplo 4:

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

Ejemplo 5:

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

La resolución de problemas:

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 # 都配对了则栈为空  如果栈不为空则说明未配对
Publicado 24 artículos originales · ganado elogios 0 · Vistas 416

Supongo que te gusta

Origin blog.csdn.net/qq_18138105/article/details/105167805
Recomendado
Clasificación