Stacks and queuesstack-valid-parentheses
LessonΒ·difficulty 3/5Β·~15 min
Stacks: valid parentheses
Stacks: valid parentheses
A stack is a last-in, first-out pile. A Python list is already a stack:
python
stack = []
stack.append("(") # push
stack[-1] # "(" β peek at the top
stack.pop() # "(" β remove and return the top
Stacks are perfect for matching nested brackets: the most recently opened bracket must be the first one to close. This is LeetCode #20.
Your task
Write is_valid(s) where s contains only the characters ()[]{}. Return
True if and only if every bracket is closed by the matching kind in the
correct order.
python
is_valid("()[]{}") # True
is_valid("(]") # False (wrong kind)
is_valid("([)]") # False (wrong order)
is_valid("") # True (nothing unbalanced)
Hint: push every opening bracket. When you meet a closing bracket, the top of the stack must be its matching opener β otherwise it is invalid. At the end the stack must be empty.
Tests
- all kinds matched
- wrong kind
- wrong order
- empty string
- nested ok (hidden)
- unclosed opener (hidden)
Stuck? Ask for a spark
warming up
Loading editorβ¦
$ Console output will appear here.