当前位置:网站首页>LeetCode#20. Valid parentheses

LeetCode#20. Valid parentheses

2022-06-22 21:34:00 Rufeng ZHHH

Given one only includes '(',')','{','}','[',']' String s , Determines whether the string is valid .

Valid string needs to meet :

Opening parentheses must be closed with closing parentheses of the same type .
The left parenthesis must be closed in the correct order .

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

author : Power button (LeetCode)
link : Power button  

First, through analysis, we know that to satisfy this valid bracket , You must make the three possible parentheses given in the title close . Therefore, it is appropriate to use the stack method to complete this topic . I have previously written articles about stack knowledge Python The order sheet ( list ) Construction stack _ As the wind Zhhh The blog of -CSDN Blog Python The order sheet ( list ) Construction stack https://blog.csdn.net/qq_60926106/article/details/125286009?spm=1001.2014.3001.5502 Ideas as follows :

        ①. You can do a rough screening first , If the given string ( Here we use s To represent this string )s The length of is equal to 0 Or an odd number , Then you can go back directly False 了 , Because if the parentheses want to form a closure ,s The length of can only be an even number .

        ②. about s Not for 0 And even numbers , Let's make the following judgment :

                1. Traverse the whole s, If the traversed element i (for i in s) by "("  "{"  "["  Any one of , We can put their corresponding ")"  "}"  "]"  Pressing stack ( The premise is that we first create a list as our stack ). If i The elements encountered are ")"  "}"  "]" , We can perform stack out operation , See if the pop-up element is consistent with i equal , Then judge . If equal , Then continue the cycle , If not equal , Go straight back to False that will do .     

                2. At the end of the cycle , If the element in the stack is 0, Then it means that all the parentheses are closed , Can return True, Otherwise it returns False.

The code is as follows :       

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

原网站

版权声明
本文为[Rufeng ZHHH]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206222006499456.html