Advertisement
LardaX

BalancedParenthesis

Jan 22nd, 2017
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.00 KB | None | 0 0
  1. import java.util.ArrayDeque;
  2. import java.util.Deque;
  3. import java.util.Scanner;
  4.  
  5. public class BalancedParenthesis {
  6.     public static void main(String[] args) {
  7.         Scanner scanner = new Scanner(System.in);
  8.         char[] parenthesis = scanner.nextLine().toCharArray();
  9.  
  10.         Deque<Integer> roundParenthesis = new ArrayDeque<>();
  11.         Deque<Integer> squareParenthesis = new ArrayDeque<>();
  12.         Deque<Integer> curlyParenthesis = new ArrayDeque<>();
  13.  
  14.         for (int endIndex = 0; endIndex < parenthesis.length; endIndex++) {
  15.             char parenthesi = parenthesis[endIndex];
  16.             Integer startIndex = -1;
  17.             switch (parenthesi) {
  18.                 case '{': curlyParenthesis.push(endIndex); break;
  19.                 case '[': squareParenthesis.push(endIndex); break;
  20.                 case '(': roundParenthesis.push(endIndex); break;
  21.  
  22.                 case '}':
  23.                     startIndex = curlyParenthesis.poll();
  24.                     if (startIndex == null || (startIndex + endIndex) % 2 != 1){
  25.                         System.out.println("NO");
  26.                         return;
  27.                     }
  28.                     break;
  29.  
  30.                 case ']':
  31.                     startIndex = squareParenthesis.poll();
  32.                     if (startIndex == null || (startIndex + endIndex) % 2 != 1){
  33.                         System.out.println("NO");
  34.                         return;
  35.                     }
  36.                     break;
  37.  
  38.                 case ')':
  39.                     startIndex = roundParenthesis.poll();
  40.                     if (startIndex == null || (startIndex + endIndex) % 2 != 1){
  41.                         System.out.println("NO");
  42.                         return;
  43.                     }
  44.                     break;
  45.             }
  46.         }
  47.  
  48.         if (roundParenthesis.isEmpty() && squareParenthesis.isEmpty() && curlyParenthesis.isEmpty()) {
  49.             System.out.println("YES");
  50.         } else {
  51.             System.out.println("NO");
  52.         }
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement