Checking for the balanced parenthesis in java using stack :
Example :
([]) — balanced parenthesis
{}[] — balanced parenthesis
()) — unbalanced parenthesis
Code :
Explanation for the code :
This problem “checking for the balanced parenthesis” has some special constraint. The recently opened parenthesis has to be closed first. This follows “LIFO”. This can solved using stack data structure.
A fresh new stack is created and a loop is iterating over the string which contains parenthesis.
Note: [] , {}, () are only possible.
The characters in the string are pushed into the stack until a closed parenthesis is encountered. When a closed parenthesis is encountered, then we check for the isEmpty() condition. The encountered closed parenthesis and the element on the top of the stack are passed to a function. We check whether the both characters are same . If yes , we pop the top element in the stack.
If the stack is empty, that means the string only contains balanced parenthesis.