Advertisement
Spocoman

06. Balanced Brackets

Oct 20th, 2024
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.85 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. class Main {
  4.     public static void main(String[] args) {
  5.         Scanner scanner = new Scanner(System.in);
  6.         int n = Integer.parseInt(scanner.nextLine()),
  7.             openBrackets = 0;
  8.         String bracket = "";
  9.  
  10.         for (int i = 0; i < n; i++) {
  11.             bracket = scanner.nextLine();
  12.             if (bracket.equals(")")) {
  13.                 openBrackets--;
  14.                 if (openBrackets < 0) {
  15.                     break;
  16.                 }
  17.             } else if (bracket.equals("(")) {
  18.                 openBrackets++;
  19.                 if (openBrackets > 1) {
  20.                     break;
  21.                 }
  22.             }
  23.         }
  24.        
  25.         if (openBrackets == 0) {
  26.             System.out.println("BALANCED");
  27.         } else {
  28.             System.out.println("UNBALANCED");
  29.         }
  30.     }
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement