Balanced Brackets in an expression using Stack

Balanced Brackets in an expression (well-formedness) using Stack

by Sandeep Kumar

HTML

<div id="banner-message">
  <div id="divInput">
    <input type="text" id="inpExpression" placeholder="Enter the expression" />
  </div>
  <button>Search Number</button>
  <br />
  <span id="spanResult"></span>
</div>

CSS

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}

#divInput {
  padding: 5px;
  margin-bottom: 5px;
}

#spanCubeRoot {
  padding: 5px;
  margin-top: 5px;
}

JavaScript

// 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);
}