Valid Parentheses
Stack
Problem
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.
Constraints:
1 <= s.length <= 104sconsists of parentheses only'()[]{}'.
For example:
Input: s = "()"
Output: trueInput: s = "()[]{}"
Output: trueInput: s = "(]"
Output: falseInput: s = "([)]"
Output: falseInput: s = "{[]}"
Output: trueThought Process
This is a stack problem because we need to check when we come across a closing bracket, if the previous element was an opening bracket. Since stacks can keep track of the last viewed element, a stack is perfect for this scenario.
We need to use a stack to make sure the previous viewed element is an opening bracket whenever we come across a closing bracket. This is because there always needs to be an opening bracket to a closing bracket.
We check if brackets are the same type by using a dictionary.
Solution
Time Complexity
Time: O(n)
Space: O(n)
Last updated