#K77752. Balanced Brackets Checker
Balanced Brackets Checker
Balanced Brackets Checker
You are given a string expression which may contain brackets: ()
, {}
, and []
. Your task is to determine whether the brackets in the expression are balanced. An expression is considered balanced if:
- Every opening bracket has a corresponding closing bracket.
- Brackets are closed in the correct order.
For instance, the expression ([]){}
is balanced, while [(])
is not.
Note: The expression may contain non-bracket characters which should be ignored.
The classic algorithm utilizes a stack data structure. When an opening bracket is encountered, it is pushed onto the stack. When a closing bracket is encountered, the algorithm checks whether the top of the stack contains the corresponding opening bracket. If it does, it pops the stack; otherwise, the expression is unbalanced.
You can refer to the following mathematical recital for the concept of balanced brackets:
\( \text{For every } x \in \{ (, {, [ \}, \exists y \in \{ ), }, ] \} \text{ such that } \; \text{match}(x, y) \) where \(\text{match}(x,y)\) is defined appropriately.
inputFormat
The input consists of a single line containing a string expression
. The string may include any printable characters.
Example:
([]){}
outputFormat
Output a single line: True
if the brackets in the expression are balanced, and False
otherwise.
Example:
True## sample
()
True