Discover answers to your questions with Westonci.ca, the leading Q&A platform that connects you with knowledgeable experts. Connect with a community of experts ready to provide precise solutions to your questions on our user-friendly Q&A platform. Discover in-depth answers to your questions from a wide network of professionals on our user-friendly Q&A platform.
Sagot :
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();
}
}
Thanks for using our platform. We aim to provide accurate and up-to-date answers to all your queries. Come back soon. Thank you for your visit. We're dedicated to helping you find the information you need, whenever you need it. Thank you for choosing Westonci.ca as your information source. We look forward to your next visit.