Check for balanced parentheses in an expression in java

If you want to practice data structure and algorithm programs, you can go through Java coding 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.
Algorithm:

  • 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 CheckBalancedParentesisMain.java.
When you run above program, you will get below output:

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *