Advertisement
Sim0o0na

Untitled

Jan 25th, 2017
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. package com.company;
  2.  
  3. import java.util.ArrayDeque;
  4. import java.util.Scanner;
  5.  
  6. /**
  7. * Created by Simona Simeonova on 25-Jan-17.
  8. */
  9. public class BalancedParenthesis {
  10. public static void main(String[] args) {
  11. Scanner scan = new Scanner(System.in);
  12. String input = scan.nextLine();
  13. if(CheckParentesis(input)){
  14. System.out.print("YES");
  15. }else{
  16. System.out.print("NO");
  17. }
  18. }
  19. public static boolean CheckParentesis(String str)
  20. {
  21. if (str.isEmpty())
  22. return true;
  23.  
  24. ArrayDeque<Character> stack = new ArrayDeque<>();
  25. for (int i = 0; i < str.length(); i++)
  26. {
  27. char current = str.charAt(i);
  28. if (current == '{' || current == '(' || current == '[')
  29. {
  30. stack.push(current);
  31. }
  32.  
  33. if (current == '}' || current == ')' || current == ']')
  34. {
  35. if (stack.isEmpty())
  36. return false;
  37.  
  38. char last = stack.peek();
  39. if (current == '}' && last == '{' || current == ')' && last == '(' || current == ']' && last == '[')
  40. stack.pop();
  41. else
  42. return false;
  43. }
  44. }
  45.  
  46. return stack.isEmpty();
  47. }
  48.  
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement