/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main
(String[] args
) { System.
out.
println("enter the sequence of brackets:"); Scanner in
= new Scanner
(System.
in); //String s = in.nextLine();
String s
= "((({{{[[[]]]}}})))"; String s2
= "(([{{{[[[]]]}}})))"; System.
out.
println(s
+ " is " + new Parentheses
().
isBalanced(s
)); System.
out.
println(s2
+ " is " + new Parentheses
().
isBalanced(s2
)); }
}
class Parentheses {
private static final char LEFT_PAREN = '(';
private static final char RIGHT_PAREN = ')';
private static final char LEFT_BRACE = '{';
private static final char RIGHT_BRACE = '}';
private static final char LEFT_BRACKET = '[';
private static final char RIGHT_BRACKET = ']';
public static boolean isBalanced
(String s
) { Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == LEFT_PAREN) stack.push(LEFT_PAREN);
if (s.charAt(i) == LEFT_BRACE) stack.push(LEFT_BRACE);
if (s.charAt(i) == LEFT_BRACKET) stack.push(LEFT_BRACKET);
if (s.charAt(i) == RIGHT_PAREN) {
if (stack.isEmpty()) return false;
if (stack.pop() != LEFT_PAREN) return false;
} else if (s.charAt(i) == RIGHT_BRACE) {
if (stack.isEmpty()) return false;
if (stack.pop() != LEFT_BRACE) return false;
} else if (s.charAt(i) == RIGHT_BRACKET) {
if (stack.isEmpty()) return false;
if (stack.pop() != LEFT_BRACKET) return false;
}
}
return stack.isEmpty();
}
}