Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does python judge valid parentheses

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

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!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report