Parenthesis refers to the different kind of brackets which are available to us and are also referred as Braces. These are the ones- ‘{‘ ‘}’ ‘(‘ ‘)’ ‘[‘ ‘]’ ‘<‘ ‘>’ named as Curly, round, square and angular braces.
Problem
For a given string as input write a program to check if the sequence of braces in string is balanced or not. Some sample cases are given.
Input string — “{ { [ ( < ( ) > ) ] } }”
Output string — “Balanced”
Input string — “< { [ ] } >”
Output string — “Balanced”
Input string — “{ ( { ) > ) } }”
Output string — “Unbalanced”
Input string — “techdose { is gro[ ]wing (very fast ) }”
Output string — “Balanced”
This is easily the seen application used in operating systems and compilers. We see daily in our code the braces must be balanced and to check compiler does have some program. If the parenthesis are not balanced we get some error. So here is the detailed solution for the implementation of this problem. The explanation is given as the comments in the program as well.
Explanation
Explaining the ‘isbalanced()’ function of the program.
A string s is passed as argument in the method. At first a stack ‘st’ of character type is declared. Next the input string is traversed and when the open braces is found in the string just push it in stack. By doing so we will get all the open bracket first and now while traversing further in string whenever we find closing braces we check the top of the stack and if the top of the stack is the opening pair of the current closing braces then we pop the top of stack and continue with our string. But if suppose we don’t get the matching opening pair at the top then we can just return “Unbalanced” and the program ends. Returning the string will stop the further actions as it is not necessary to continue with the string.
Here is the code.
This article has been contributed by Thakurnik