Leetcode 20: Valid Parentheses

Title:
Insert picture description here
Insert picture description here
python code:

class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        for i in range(len(s)):
            character = s[i]
            if character != '(' and character != "{" and character != '[' and character != ")" and character != ']' and character != '}':
                continue
            if character == "(" or character == "{" or character == '[':
                stack.append(character)
                continue
            elif character == ')' and (len(stack) == 0 or stack[-1] != '('):
                return False
            elif character == ']' and (len(stack) == 0 or stack[-1] != '['):
                return False
            elif character == '}' and (len(stack) == 0 or stack[-1] != '{'):
                return False
            stack.pop() 
        return not len(stack)

The code uses the classic stack idea to achieve

The special results are as follows:
Insert picture description here

Insert picture description here
Insert picture description here
If you feel good, please like and follow the message.
Thank you~

Guess you like

Origin blog.csdn.net/BSCHN123/article/details/112390243