#K7876. Balancing Brackets
Balancing Brackets
Balancing Brackets
You are given a string s consisting of the characters ('
, ['
, )
, and ]
. Your task is to determine the minimum number of moves required to make the string balanced.
A string is considered balanced if every opening bracket has a corresponding closing bracket of the same type and the brackets are closed in the correct order. In other words, the string is balanced if, when processed from left to right, every closing bracket matches the most recent unmatched opening bracket, and no unmatched opening brackets remain.
For example:
- For
([])
, the string is already balanced, so the answer is 0. - For
([)]
, two moves are required to balance the string.
Note: If there is a mismatched or extra bracket, you must count a move to either remove or insert a matching bracket in order to balance the string.
The answer can be thought of in terms of the following idea: if we denote the number of required moves as m, then
[ m = (\text{number of unmatched closing brackets}) + (\text{number of unmatched opening brackets}) ]
inputFormat
A single line input containing the string consisting solely of the characters (, ), [, and ].
outputFormat
A single integer which is the minimum number of moves required to balance the string.## sample
([])
0