import java.util.*; public class ParenBalancing3 { public static void main (String[] argv) { // Test 1. String s = "([()])"; checkParens (s); // Test 2. s = "[][()]()"; checkParens (s); // Test 3. s = "((())]"; checkParens (s); // Test 4. s = "[)(]"; checkParens (s); } static void checkParens (String inputStr) { char[] letters = inputStr.toCharArray(); Stack stack = new Stack (); boolean unbalanced = false; for (int i=0; i unbalanced. unbalanced = true; break; } } else if (letters[i] == ']') { // We should have a '[' match on the stack char ch = ']'; if (! stack.isEmpty() ) { ch = stack.pop (); } if (ch != '[') { // Not matched. unbalanced = true; break; } } } // end-for if ( (unbalanced) || (! stack.isEmpty()) ) { System.out.println ("String " + inputStr + " has unbalanced parens"); } else { System.out.println ("String " + inputStr + " has balanced parens"); } } }