Stack: Program to check if brackets are balanced



Write a program to check if the expression containing brackets are balanced or not

A series of brackets are balanced if for each opening bracket, there is a closing bracket of same type and at the relevant position
For e.g.
             '{[]}' - This is balanced brackets
             '[{]()' - This is not balanced brackets

 
General Idea
  • Identify a bracket as an opening bracket or a closing bracket
  • Use a stack
  • When we encounter a open bracket we push that bracket in the stack
  • When we encounter a closing bracket we pop the bracket from stack
  • If the popped bracket is of same type as the closing bracket, we continue
  • If not, the series of brackets are not balanced and so we stop
 
Java Code
import java.util.Stack;

class Balancebrackets{
    Stack<Character> stack = new Stack<>();
    
    static char[][] stored = {{'{','}'},{'[',']'},{'(',')'}};
     
    public static boolean isOpenTerm(char item){  
        for(char[] d : stored){                   
            if(d[0] == item){
                return true;            
            }
        }
        
        return false;
    }

    public static boolean matches(char popped, char item){ 
        for(char[] d : stored){
            if(d[0] == popped){
                return d[1] == item;
            }
        }

        return false;
    }

    public boolean isBalanced(String data){
        for(char c : data.toCharArray()){
            if(isOpenTerm(c)){
                stack.push(c);
            }else{
                if(stack.isEmpty()){
                    return false;
                }
                char popped = stack.pop();

                if(matches( popped, c)){
                    continue;
                }
                else{
                    return false;
                }
            }
        }

        return stack.isEmpty();
    }

    public static void main(String args[]){

        Balancebrackets bb = new Balancebrackets();

        String one = "{}[]{[()]}";
        String two = "{}{[]";

        System.out.println("The string " + one + " is balanced: " + bb.isBalanced(one));
        System.out.println("The string " + two + " is balanced: " + bb.isBalanced(two));
    
    }
}

 



Thanks for feedback.



Read More....
Implement a stack using queue
Reverse a stack using recursion
Stack Introduction Program