Given an expression string exp, write a program to check whether the brackets {}, (), and [] are balanced and properly nested. An expression is considered balanced if every opening bracket has a corresponding closing bracket in the correct order.
Example:
Input:
"[()]{}{[()()]()}"
Output:
Balanced
Input:
"[(])"
Output:
Not Balanced
Algorithm:
- Declare a character stack S.
- Traverse the expression string exp.
- If the current character is a starting bracket (, {, or [, push it to the stack.
- If the current character is a closing bracket ), }, or ], pop from the stack and check if it matches the corresponding opening bracket; if not, the brackets are not balanced.
- After traversal, if the stack is not empty, the brackets are not balanced.
Below image is a dry run of the above approach:
👁 ImageCode Implementation
Explanation:
- function "areBracketsBalanced" checks if brackets in a string are balanced using a stack.
- stack "s" is used to store opening brackets.
- Traverse each character of the expression.
- Push opening brackets '(', '[', '{' onto the stack.
- For closing brackets ')', ']', '}', pop the top element and check if it matches the corresponding opening bracket.
- If it does not match, return false.
- After traversal, return true if the stack is empty, otherwise return false.