Given a string
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.
Output: true
Output: true
Output: true
Constraints:
0 <= s.length <= 104 s consists of parentheses only'()[]{}' .
Contents
Solution 1 - Using stack to store opening parentheses, and check its validity when a closing parentheses occurrs
In this approach, we are going to use a
Implementation steps:
-
First, we will create two variables
chars aStack that we will use to store opening brackets, andcloseToOpenMap a Map with closing and corresponding opening bracket pair. -
Next, loop through input string
s characters and check if the characters one of the closing bracket, if it is then check if the stack is not empty and the top element is the corresponding opening bracket, if it is then pop the top element, otherwise returnfalse . -
If the current character is an opening bracket, then simply add it to the stack
chars . -
Finally, check if the stack is empty, if it is empty return
true , otherwise returnfalse . (If every opening bracket has a valid corresponding closing bracket, then stack will be empty at the end)
Complexity Analysis:
Time complexity: Above code runs in O(n) time where
Space complexity: O(n), since we are storing opening brackets into a
Above implementations source code can be found at