Answer:
Explanation:
import java.util.*;
public class BalancedBrackets {
// function to check if brackets are balanced
static boolean isBalanced(String expr)
{
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < expr.length(); i++)
{
char x = expr.charAt(i);
if (x == '(' || x == '[' || x == '{')
{
// Push the element in the stack
stack.push(x);
continue;
}
if (stack.isEmpty())
return false;
char 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.isEmpty());
}
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("\nEnter the expression to check is balanced or not !");
String expr = scan.nextLine();
boolean output;
output = isBalanced(expr);
System.out.println(output);
if (output)
System.out.println("Balanced ");
else
System.out.println("Not Balanced ");
scan.close();
}
}