Here is the original problem, and below is my solution. I wonder what can be improved? Or is there a fundamentally better algorithm out there? Thank you! My intuition is telling me that it can be more concise and efficient than this.
Input Format
The first line contains a single integer, , denoting the number of strings. Each line of the subsequent lines consists of a single string, , denoting a sequence of brackets.
Output Format
For each string, print whether or not the string of brackets is balanced on a new line. If the brackets are balanced, print YES; otherwise, print NO.
function main() {
var t = parseInt(readLine());
var i, isBalanced, stack, exp, len
for (var a0 = 0; a0 < t; a0++) {
exp = readLine().split('');
stack = [];
isBalanced = true;
i = -1;
len = exp.length;
while (++i < len) {
switch (exp[i]) {
case "{":
case "[":
case "(":
stack.push(exp[i])
break;
case "}":
if (stack.pop() !== "{") {
isBalanced = false
}
break;
case "]":
if (stack.pop() !== "[") {
isBalanced = false
}
break;
case ")":
if (stack.pop() !== "(") {
isBalanced = false
}
break;
default:
}
if (isBalanced === false) {
console.log("NO")
break;
}
}
if (isBalanced === true) {
if (stack.length > 0) {
if (stack[0] === "{" || stack[0] === "[" || stack[0] === "(") {
console.log("NO")
}
} else {
console.log("YES");
}
}
}
}