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
Constraints:
1 <= s.length <= 104
s
consists of parentheses only'()[]{}'
.
Solution
/**
* @param {string} s
* @return {boolean}
*/
var isValid = function(s) {
let opentags = new Array();
for(let i = 0; i<s.length;i++){
if(i == 0 && (s[i] == "]" || s[i] == "}" || s[i] == ")")){
return false;
}
switch(s[i])
{
case "]":
let lastElem = opentags.pop();
if(lastElem != "["){
return false;
}
break;
case "}":
let lastElema = opentags.pop();
if(lastElema != "{"){
return false;
}
break;
case ")":
let lastElemb = opentags.pop();
if(lastElemb != "("){
return false;
}
break;
default:
opentags.push(s[i]);
break;
}
}
if(opentags.length > 0){
return false;
}
return true;
};
A freelance web developer with a decade of experience in creating high-quality, scalable web solutions. His expertise spans PHP, WordPress, Node.js, MySQL, MongoDB, and e-commerce development, ensuring a versatile approach to each project. Aadi’s commitment to client satisfaction is evident in his track record of over 200 successful projects, marked by innovation, efficiency, and a customer-centric philosophy.
As a professional who values collaboration and open communication, Aadi has built a reputation for delivering projects that exceed expectations while adhering to time and budget constraints. His proactive and problem-solving mindset makes him an ideal partner for anyone looking to navigate the digital landscape with a reliable and skilled developer.