I want to test if an input String is balanced. It would be balanced if there is a matching opening and closing parenthesis, bracket or brace.
example:
{} bal
Yes, a stack is a suitable choice for the task, or you could use a recursive function. If you use a stack, then the idea is you push each opening bracket on the stack, when you encounter a closing bracket you check that the top of the stack matches it. If it matches, pop it off, if not that is an error. When complete, the stack should be empty.
import java.util.Stack;
public class Balanced {
public static boolean isBalanced(String in)
{
Stack st = new Stack();
for(char chr : in.toCharArray())
{
switch(chr) {
case '{':
case '(':
case '[':
st.push(chr);
break;
case ']':
if(st.isEmpty() || st.pop() != '[')
return false;
break;
case ')':
if(st.isEmpty() || st.pop() != '(')
return false;
break;
case '}':
if(st.isEmpty() || st.pop() != '{')
return false;
break;
}
}
return st.isEmpty();
}
public static void main(String args[]) {
if(args.length != 0) {
if(isBalanced(args[0]))
System.out.println(args[0] + " is balanced");
else
System.out.println(args[0] + " is not balanced");
}
}
}