How to check if a String is balanced?

Following is a Java code sample to detect if a string is balanced.

http://introcs.cs.princeton.edu/java/43stack/Parentheses.java.html

The idea is that -

  • For each opening brace ( [ {, push it on the stack.
  • For closing brace ) ] }, try to pop a matching opening brace ( [ } from stack. If you can't find a matching opening brace, then string is not balanced.
  • If after processing the complete string, stack is empty then string is balanced. Otherwise string is not balanced.

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<Character> st = new Stack<Character>();

        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");
        }
    }
}

1) For every opening bracket: { [ ( push it to the stack.

2) For every closing bracket: } ] ) pop from the stack and check whether the type of bracket matches. If not return false;

i.e. current symbol in String is } and if poped from stack is anything else from { then return false immediately.

3) If end of line and stack is not empty, return false, otherwise true.