fork(1) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main(String[] args) {
  11. System.out.println("enter the sequence of brackets:");
  12. Scanner in = new Scanner(System.in);
  13. //String s = in.nextLine();
  14. String s = "((({{{[[[]]]}}})))";
  15. String s2 = "(([{{{[[[]]]}}})))";
  16. System.out.println(s + " is " + new Parentheses().isBalanced(s));
  17. System.out.println(s2 + " is " + new Parentheses().isBalanced(s2));
  18. }
  19. }
  20. class Parentheses {
  21. private static final char LEFT_PAREN = '(';
  22. private static final char RIGHT_PAREN = ')';
  23. private static final char LEFT_BRACE = '{';
  24. private static final char RIGHT_BRACE = '}';
  25. private static final char LEFT_BRACKET = '[';
  26. private static final char RIGHT_BRACKET = ']';
  27.  
  28. public static boolean isBalanced(String s) {
  29. Stack<Character> stack = new Stack<Character>();
  30. for (int i = 0; i < s.length(); i++) {
  31. if (s.charAt(i) == LEFT_PAREN) stack.push(LEFT_PAREN);
  32. if (s.charAt(i) == LEFT_BRACE) stack.push(LEFT_BRACE);
  33. if (s.charAt(i) == LEFT_BRACKET) stack.push(LEFT_BRACKET);
  34.  
  35. if (s.charAt(i) == RIGHT_PAREN) {
  36. if (stack.isEmpty()) return false;
  37. if (stack.pop() != LEFT_PAREN) return false;
  38. } else if (s.charAt(i) == RIGHT_BRACE) {
  39. if (stack.isEmpty()) return false;
  40. if (stack.pop() != LEFT_BRACE) return false;
  41. } else if (s.charAt(i) == RIGHT_BRACKET) {
  42. if (stack.isEmpty()) return false;
  43. if (stack.pop() != LEFT_BRACKET) return false;
  44. }
  45. }
  46. return stack.isEmpty();
  47. }
  48. }
Success #stdin #stdout 0.09s 380736KB
stdin
Standard input is empty
stdout
enter the sequence of brackets:
((({{{[[[]]]}}}))) is true
(([{{{[[[]]]}}}))) is false