Home » Data Structure & Algorithms » Check for balanced parentheses in an expression using stack

Check for balanced parentheses in an expression using stack

Question :

WAP to check for balanced parentheses in an expression.

Algorithm :

Iterative Solution :
Step 1 : Traverse the expression string blncParenthesis.If the current character is a opening bracket (‘(‘ or ‘{‘ or ‘[‘)     then push it to a Stack stack.If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack. If the popped character is the matching opening bracket then fine else parenthesis are not balanced.
Step 2 : After complete traversal of the expression, if there is opening bracket left in stack or if the stack is not empty,  then the expression is not having balanced parenthesis.

Program :

Output :

 
 


Leave a comment

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

20 − 13 =