check for balanced parentheses in an expression in java

If you want to practice data structure and algorithm programs, you can go through data structure and algorithm interview questions.
In this post, we will see how to check for balanced parentheses in an expression.
Lets say, you have expression as a*(b+c)-(d*e)
If you notice, above expression have balanced parentheses.
Lets take another expression as (a*(b-c)*(d+e)
If you observe, above expression does not have balanced parentheses.
We will use stack data structure to check for balanced parentheses.
  • Whenever you encounter current character as ( or { or [, push it into the stack.
  • Whenever you encounter current character as ) or } or ], retrieve last element from stack and check if current character is in pair with last character retrieved from stack and if it is not in pair then expression is not balanced.
  • If we have empty stack in the end, it is balanced parentheses, else it is not balanced parentheses.

Java Program to check for balanced parentheses:

Create a main Class called
package org.arpit.java2blog;

import java.util.Stack;

public class CheckBalancedParentesisMain {

 public static void main(String[] args) {
  String checkBalancedExpr1=checkBalancedParentesis("a*(b+c)-(d*e)");
  System.out.println("a*(b+c)-(d*e) : "+checkBalancedExpr1);
  String checkBalancedExpr2=checkBalancedParentesis("(a*(b-c)*{d+e}");
  System.out.println("(a*(b-c)*{d+e} : "+checkBalancedExpr2);
 public static String checkBalancedParentesis(String expr)
     if (expr.isEmpty())
         return "Balanced";

     Stack<Character> stack = new Stack<Character>();
     for (int i = 0; i < expr.length(); i++)
         char current = expr.charAt(i);
         if (current == '{' || current == '(' || current == '[')
         if (current == '}' || current == ')' || current == ']')
             if (stack.isEmpty())
                 return "Not Balanced";
             char last = stack.peek();
             if (current == '}' && last == '{' || current == ')' && last == '(' || current == ']' && last == '[')
                 return "Not Balanced";
     return stack.isEmpty()?"Balanced":"Not Balanced";

When you run above program, you will get below output:
a*(b+c)-(d*e) : Balanced
(a*(b-c)*{d+e} : Not Balanced

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus


Java tutorial for beginners Copyright © 2012