Advertisement
Kulas_Code20

greeks

Sep 17th, 2021
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.39 KB | None | 0 0
  1. // Java program for checking
  2. // balanced brackets
  3. import java.util.*;
  4.  
  5. public class BalancedBrackets {
  6.  
  7.     // function to check if brackets are balanced
  8.     static boolean areBracketsBalanced(String expr)
  9.     {
  10.         // Using ArrayDeque is faster than using Stack class
  11.         Deque<Character> stack
  12.             = new ArrayDeque<Character>();
  13.  
  14.         // Traversing the Expression
  15.         for (int i = 0; i < expr.length(); i++)
  16.         {
  17.             char x = expr.charAt(i);
  18.  
  19.             if (x == '(' || x == '[' || x == '{')
  20.             {
  21.                 // Push the element in the stack
  22.                 stack.push(x);
  23.                 continue;
  24.             }
  25.  
  26.             // If current character is not opening
  27.             // bracket, then it must be closing. So stack
  28.             // cannot be empty at this point.
  29.             if (stack.isEmpty())
  30.                 return false;
  31.             char check;
  32.             switch (x) {
  33.             case ')':
  34.                 check = stack.pop();
  35.                 if (check == '{' || check == '[')
  36.                     return false;
  37.                 break;
  38.  
  39.             case '}':
  40.                 check = stack.pop();
  41.                 if (check == '(' || check == '[')
  42.                     return false;
  43.                 break;
  44.  
  45.             case ']':
  46.                 check = stack.pop();
  47.                 if (check == '(' || check == '{')
  48.                     return false;
  49.                 break;
  50.             }
  51.         }
  52.  
  53.         // Check Empty Stack
  54.         return (stack.isEmpty());
  55.     }
  56.  
  57.     // Driver code
  58.     public static void main(String[] args)
  59.     {
  60.         String expr = "[}}]";
  61.  
  62.         // Function call
  63.         if (areBracketsBalanced(expr))
  64.             System.out.println("Balanced ");
  65.         else
  66.             System.out.println("Not Balanced ");
  67.     }
  68. }
  69.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement