#K76372. Balanced Brackets
Balanced Brackets
Balanced Brackets
You are given a string s consisting of various characters including open and close brackets: ( )
, { }
, and [ ]
. Your task is to determine whether the brackets in the string are balanced. A string is considered balanced if:
- Every opening bracket has a corresponding closing bracket.
- Brackets are closed in the correct order.
For instance, the string "{[()()]}"
is balanced, while "(]"
is not.
Note: Other characters in the string should be ignored.
Mathematical Description:
Let \( S = s_1 s_2 \ldots s_n \) be a string of characters. Define a mapping for closing to opening brackets as \( f(\text{')'}) = ( \), \( f(\text{'}'}) = { \), \( f(\text{']'}) = [ \). The string is balanced if for each closing bracket \( s_j \), there exists an earlier index \( i \) such that \( s_i = f(s_j) \) and the substring between them is also balanced.
inputFormat
The input consists of a single line containing the string s which may include letters, digits, spaces, and bracket characters.
outputFormat
Output a single line: True
if the brackets are balanced, otherwise False
.
()
True