SIRAKOV4444

Untitled

May 27th, 2020
422
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.34 KB | None | 0 0
  1. import java.util.ArrayDeque;
  2. import java.util.Collection;
  3. import java.util.Collections;
  4. import java.util.Scanner;
  5.  
  6. public class Lab {
  7. public static void main(String[] args) {
  8. Scanner sc = new Scanner(System.in);
  9.  
  10. String sequence = sc.nextLine();
  11. ArrayDeque<Character> stack = new ArrayDeque<>();
  12. boolean areBalanced = true;
  13. for (int i = 0; i < sequence.length(); i++) {
  14. char current = sequence.charAt(i);
  15. if (current == '[' || current == '{' || current == '(') {
  16. stack.push(current);
  17. } else {
  18. if (stack.isEmpty()) {
  19. areBalanced = false;
  20. break;
  21. }
  22. char topElement = stack.pop();
  23. if (current == ']' && topElement != '[') {
  24. areBalanced = false;
  25. break;
  26. } else if (current == '}' && topElement != '{') {
  27. areBalanced = false;
  28. break;
  29. } else if (current == ')' && topElement != '(') {
  30. areBalanced = false;
  31. break;
  32. }
  33. }
  34. }
  35. if (areBalanced) {
  36. System.out.println("YES");
  37. } else {
  38. System.out.println("NO");
  39. }
  40. }
  41. }
Add Comment
Please, Sign In to add comment