The Question is from the interview section of leetcode and is marked as easy difficult. Here is the description:
The 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.
Example 1:
Input: s = "()" Output: true
Example 2:
Input: s = "()[]{}" Output: true
Example 3:
Input: s = "(]" Output: false
The Solution
var ValidParenthesis = function(str) {
if(str.length == 1){
return false;
}
let obj = {
'(': ')',
'{': '}',
'[': ']'
}
let objKeys = ['(', '{', '['];
let arr = [];
let length = str.length;
let i = 0;
while(i<length){
if(objKeys.includes(str[i])){
arr.push(str[i]);
i++;
}else{
let ch = arr.pop();
if(ch=='(' && str[i] == ')' || ch=='[' && str[i] == ']' || ch=='{' && str[i] == '}'){
i++;
}else{
return false;
}
}
}
if(arr.length == 0){
return true;
}else{
return false;
}
};
Watch the video for a full code walkthrough and optimisation steps. If you do have any questions or feedback feel free to add comments.
Be First to Comment