📘
Valid Parentheses
Given a string s containing just the characters '(', ')', '{', '}', '[', and ']', determine if the input string is valid.
An input string is valid if:
- Open brackets are closed by the same type of brackets
- Open brackets are closed in the correct order
Example:
Input:
()[]{}Output:
True
Reasoning:
- The input string
()[]{}is processed from left to right, with each opening bracket being pushed onto a stack. - When a closing bracket is encountered, the top of the stack is checked to ensure it contains the corresponding opening bracket:
(matches),{matches}, and[matches]. - The string is valid if the stack is empty at the end, meaning all brackets were properly closed:
()is closed,[]is closed, and{}is closed. - Since all brackets in the input string are properly closed in the correct order, the output is
True.
Constraints:
- 1 <= len(s) <= 10^4
- s consists of parentheses only
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.