// find elements
var button = $("button")
// handle click and add class
button.on("click", () => {
// Driver code
let expr = $("#inpExpression").val();
var text = areBracketsBalanced(expr)
? "Balanced"
: "Not Balanced";
$("#spanResult").text(text);
})
// Javascript program for checking
// balanced brackets
// Function to check if brackets are balanced
function areBracketsBalanced(expr)
{
// Using ArrayDeque is faster
// than using Stack class
let stack = [];
// Traversing the Expression
for(let i = 0; i < expr.length; i++)
{
let x = expr[i];
if (x == '(' || x == '[' || x == '{')
{
// Push the element in the stack
stack.push(x);
continue;
}
// If current character is not opening
// bracket, then it must be closing.
// So stack cannot be empty at this point.
if (stack.length == 0)
return false;
let check;
switch (x){
case ')':
check = stack.pop();
if (check == '{' || check == '[')
return false;
break;
case '}':
check = stack.pop();
if (check == '(' || check == '[')
return false;
break;
case ']':
check = stack.pop();
if (check == '(' || check == '{')
return false;
break;
}
}
// Check Empty Stack
return (stack.length == 0);
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.