Didart

Matching Brackets

Dec 27th, 2022
818
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.78 KB | None | 0 0
  1. package StacksAndQueues;
  2.  
  3. import java.util.ArrayDeque;
  4. import java.util.Scanner;
  5.  
  6. public class MatchingBrackets {
  7.     public static void main(String[] args) {
  8.  
  9.         Scanner scanner = new Scanner(System.in);
  10.         String expression = scanner.nextLine();
  11.         ArrayDeque<Integer> stack = new ArrayDeque<>();
  12.  
  13.         for (int i = 0; i < expression.length(); i++) {
  14.             char currentSymbol = expression.charAt(i);
  15.  
  16.             if (currentSymbol == '(') {
  17.                 stack.push(i);
  18.             } else if (currentSymbol == ')') {
  19.                 int startSymbol = stack.pop();
  20.                 String contents = expression
  21.                         .substring(startSymbol, i + 1);
  22.                 System.out.println(contents);
  23.             }
  24.         }
  25.     }
  26. }
Advertisement
Add Comment
Please, Sign In to add comment