Advertisement
SensaBG

BalancedBrackets

Aug 19th, 2024
25
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.95 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class matchingBracket {
  4.     public static void main(String[] args) {
  5.         Scanner scanner = new Scanner(System.in);
  6.         int cycles = Integer.parseInt(scanner.nextLine());
  7.  
  8.         int countOpenBrackets = 0;
  9.         boolean balanced = true;
  10.  
  11.         while (cycles-- > 0) {
  12.             String input = scanner.nextLine();
  13.  
  14.             if (input.equals("(")) {
  15.                 countOpenBrackets++;
  16.             } else if (input.equals(")")) {
  17.                 countOpenBrackets--;
  18.                 if (countOpenBrackets < 0) {
  19.                     balanced = false;
  20.                 }
  21.             }
  22.         }
  23.  
  24.         if (countOpenBrackets != 0) {
  25.             balanced = false;
  26.         }
  27.  
  28.  
  29.         if(balanced){
  30.             System.out.println("BALANCED");
  31.         } else {
  32.             System.out.println("UNBALANCED");
  33.         }
  34.  
  35.        // System.out.println(balanced ? "BALANCED" : "UNBALANCED");
  36.     }
  37. }
  38.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement