import java.util.Scanner; public class BalancedBrackets { public static void main(String[] args) { main( new Scanner(System.in) ); } public static void main(String input) { main( new Scanner(input + "\nDONE") ); } public static void main(Scanner s) { while (!s.hasNext("DONE")) { System.out.println( removeAllBalanced(s.nextLine()).equals("") ? "YES" : "NO" ); } } /* Read all balanced expressions (including those with no parens), * and return the remaining unbalanced remainder of the string. * remainder("[]{}") = "" remainder("[a]b]c") = "]c" */ static String removeAllBalanced( String s ) { if (s.equals("")) { return ""; } else { if (contains(CLOSES,first(s))) { return s; } else if (contains(OPENS,first(s))) { String body = removeAllBalanced(rest(s)); // body should start with the closing-bracket for first(s); if not s is unbalanced. return (body.equals("") || first(body) != mate(first(s))) ? s : removeAllBalanced(rest(body)); } else { // s starts with a non-bracket; skip over it. return removeAllBalanced(rest(s)); } } } static final String OPENS = "{[(<"; static final String CLOSES = "}])>"; // MUST be parallel to OPENS static boolean contains(String s, char c) { return s.contains(new Character(c).toString()); } static char mate( char opener ) { return CLOSES.charAt( OPENS.indexOf(opener) ); } static char first(String s) { return s.charAt(0); } static String rest(String s) { return s.substring(1); } }