Checking for Balanced Paranthesis using Stack in C++

Balanced equations ? Not it is not the one you see in Chemistry. Balanced equations are those equations in which the brackets in the equation are balanced. Consider the following expression :

(a+b)

This equation is balanced considered to be balanced as the closing ) matches the opening (. Consider another example below :

(a+b*{a-b))

In the above equation you could see that the opening flower bracket doesn't have an matching closing flower bracket. So this is considered to be a balanced equation. 

So lets write a program for that. We will be using stack in the program and this is one of the most important application of stack. 

Algorithm :
  • Get the expression from the user
  • Run a loop for the entire length of the expression.
  • If the character is (, { or [ then push it on to the stack,
  • If the character is ), } or ] then pop a character from the stack and check if it is (, { or [ respectively.
  • If so continue on to the next iteration of the loop else print it out as unbalanced equation.
  • After the end of the loop check if the stack is empty. If so print Balanced equation else print unbalanced equation.



Comments

Popular posts from this blog

Finding the Number of Trailing Zero's in Factorial of a Number

Finding the sum of N Biggest elements in Binary Search Tree

Finding a Single Number amongst Repeated Numbers [Repeated Twice]