20. Valid Parentheses
Easy
Description
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.
Example 1:
Example 2:
Example 3:
Example 4:
Constraints:
1 <= s.length <= 104
s consists of parentheses only '()[]{}'
Solutions
Approach: Stack
Time complexity: \(O(n)\)
Space complexity: \(O(n)\)
Way 1:
Algorithmic Way
Traverse the bracket string s
.
-
When encountering a left bracket, push the current left bracket into the stack;
-
When encountering a right bracket, pop the top element of the stack (if the stack is empty, directly return false), and judge whether it matches. If it does not match, directly return false.
At the end of the traversal,
- if the stack is empty, it means the bracket string is valid, return true; otherwise, return false.
The time complexity is O(n), and the space complexity is O(n). Here, n is the length of the bracket string .
Way 2:
Using a dictionary or hashMap
What is the difference between HashMap and HashTable in JavaScript?
Both Hash Tables and Hashmap provide a key/value functionality but there is a slight difference. Hashmap offers the ability of the keys to be of any data type, unlike Hash Tables where the keys can only be integers and strings. Also, Hashmaps can not be converted to JSON.