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.
- Every close bracket has a corresponding open bracket of the same type.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
More Examples
Follow up
- Only One Type of Parenthesis, Say ()
Solution
A typical problem which can be solved by using a stack data structure.
Version1 - When only 1 parenthesis type is present
Method 1 - Using Stack
Why Stack?
Since the last bracket that is opened must also be the first one to be closed, it makes sense to use a data structure that uses the Last In, First Out (LIFO) principle. Therefore, a stack is a good choice here.
Code
|
|
|
|
|
|
Dry Run
Lets see algo in action.
Example 1
Consider the following expression {([])}
Example 2
Example 3
Example 4
Method 2 - Using Counter When Only 1 Type of Parenthesis Present
|
|