20. Valid Parentheses
1 min read
LeetCode Daily Problem: Valid Parentheses
On this page
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.
- Every close bracket has a corresponding open bracket of the same type.
Constraints:
1 <= s.length <= 10^4sconsists of parentheses only'()[]{}'.
Approach: Stack
Lately almost every problem has been about brackets, and brackets immediately suggest a stack. This one has three bracket types, so we need to check both direction and type.
I remembered a trick I had worked out before: use a dictionary that maps each closing bracket to its opening counterpart.
Then just write the code — it is an Easy problem, after all.
python
class Solution:
def isValid(self, s: str) -> bool:
refer = {')':'(', ']':'[','}':'{'}
stack = []
for c in s:
if c in refer:
if stack and stack[-1] == refer[c]:
stack.pop()
else:
return False
else:
stack.append(c)
return len(stack) == 0Complexity
- Time and space: O(n).
SeriesDaily Problem →
TagsStack