Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Justin Bermudez
Justin Bermudez

Posted on

     

Valid Parentheses Python Solution

The problem statement is as follows:
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.

If you want to checkout the original problem gohere

So first thing you would want to know is what the different parts of a parentheses is

opening="{[("closing="}])"
Enter fullscreen modeExit fullscreen mode

we are also going to need to know the corresponding opening and closing brackets so we can put use a dictionary.

brackets={')':'(','}':'{',']':'['}
Enter fullscreen modeExit fullscreen mode

So now we can go through the actual input string and check. If the character is an opening bracket, then we can push it onto a stack.
If it is a closing, we must check if our stack is empty or not. If it is empty, then we can return False.
Otherwise, we check the most recent item we pushed onto the stack and compare it with our current item. If they are matching open and close brackets then we can pop.

forcharins:ifcharinopening:stack.append(char)elifcharinclosing:iflen(stack)==0:returnFalseifstack[-1]==brackets[char]:stack.pop()else:returnFalsereturnlen(stack)==0
Enter fullscreen modeExit fullscreen mode

full solution

defisValid(s):opening="{[("closing="}])"brackets={')':'(','}':'{',']':'['}stack=[]forcharins:ifcharinopening:stack.append(char)elifcharinclosing:iflen(stack)==0:returnFalseifstack[-1]==brackets[char]:stack.pop()else:returnFalsereturnlen(stack)==0
Enter fullscreen modeExit fullscreen mode

Top comments(2)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
erfanansari profile image
Erfan Ansari
someone who likes to learn and teach.
  • Work
    Frontend Engineer
  • Joined

in #"http://www.w3.org/2000/svg" width="20px" height="20px" viewbox="0 0 24 24">Enter fullscreen modeExit fullscreen mode

CollapseExpand
 
hrithik_singh03 profile image
𝗛𝗿𝗶𝘁𝗶𝗸 𝗦𝗶𝗻𝗴𝗵

It is showing error

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Justin Bermudez
  • Location
    SF Bay Area
  • Work
    Seeking Employment
  • Joined

More fromJustin Bermudez

Splitting a Number into Individual Digits Python
#python#beginners
Finding a Loop in a Singly Linked List in Python
#python
Move Zeroes LeetCode Python Solution
#python
DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp