0020 Valid Parentheses
Solved at: 2022-07-10
Question
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.
Solution
This is a classic stack problem.
I missed some details:
- Remember
pop()
doesn't take any argument. - Remember to check the final condition. When the list is not empty at the end, then return
False
.
class Solution:
def isValid(self, s: str) -> bool:
stack = []
opening = ["(", "{", "["]
closing = [")", "}", "]"]
for _, c in enumerate(s):
if c in opening:
stack.append(c)
continue
if not stack:
return False
e = stack.pop()
if opening.index(e) != closing.index(c):
return False
if not stack:
return True
return False