Advertisement
deyanmalinov

06. Balanced Parentheses

May 9th, 2019
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.14 KB | None | 0 0
  1. package DPM;
  2.  
  3.         import java.util.*;
  4.  
  5. public class Main {
  6.     public static void main(String[] args){
  7.         Scanner scan = new Scanner(System.in);
  8.         char[] breces = scan.nextLine().toCharArray();
  9.         if (breces.length % 2 != 0){
  10.             System.out.println("NO");
  11.             return;
  12.         }
  13.         Deque<Character> openBr = new ArrayDeque<>();
  14.         boolean isBal = true;
  15.         for (char brece : breces) {
  16.             if (brece == '{' || brece == '[' || brece == '('){
  17.                 openBr.push(brece);
  18.             }else {
  19.                 char currentBra = openBr.pop();
  20.                 if (brece == '}'){
  21.                     brece = '{';
  22.                 }
  23.                 if (brece == ']'){
  24.                     brece = '[';
  25.                 }
  26.                 if (brece == ')'){
  27.                     brece = '(';
  28.                 }
  29.                 if (brece != currentBra){
  30.                     System.out.println("NO");
  31.                     isBal = false;
  32.                     break;
  33.                 }
  34.             }
  35.         }
  36.         if (isBal){
  37.             System.out.println("YES");
  38.         }
  39.     }
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement