Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How does python judge valid parentheses

Shulou Source: shulou.com Published: 2022-05-31 14:07:56 09月16日 Update

This article introduces the relevant knowledge of "how to judge valid parentheses by python". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

[title]

Given a string that includes only'(',')','{','}','[',']', determine whether the string is valid.

A valid string must satisfy:

The left parenthesis must be closed with the same type of closing parenthesis. The left parenthesis must be closed in the correct order. Note that an empty string can be considered a valid string.

Example 1:

Enter: "()"

Output: true

Example 2:

Enter: "() [] {}"

Output: true

Example 3:

Enter: "(]"

Output: false

Example 4:

Enter: "([)]"

Output: false

Example 5:

Enter: "{[]}"

Output: true

[ideas]

Using the stack structure, traverse the string and press the stack when you encounter the left parenthesis; when you encounter the right parenthesis, you pop the stack (the left parenthesis) and determine whether the two parentheses correspond.

Note: when playing the stack, the stack may be empty!

[code]

Python version

Class Solution:

Def isValid (self, s: str)-> bool:

Stack = []

D = {

): ()

']:' ['

'}':'{'

}

For I, si in enumerate (s):

# when you encounter a closing parenthesis, determine whether there is a corresponding left parenthesis in the stack

If si in d.keys ():

If len (stack) = = 0 or stack [- 1]! = d [si]:

Return False

Else:

Stack.pop ()

# when you encounter a left parenthesis, press the stack

Else:

Stack.append (si)

Return len (stack) = = 0 "how to judge valid parentheses in python" ends here. Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Tags: Parentheses output valid character string example input content more knowledge closure utility same learning next two code dilemma practice train of thought Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn NVidia MariaDB Apple MySQL