#K52532. Balanced Brackets
Balanced Brackets
Balanced Brackets
You are given a string s
consisting only of the characters ('
and ')'
and an integer n
representing the length of the string. A sequence of brackets is said to be balanced if each opening bracket has a corresponding closing bracket and the pairs of brackets are properly nested.
The task is to determine whether the bracket sequence is balanced. Formally, the sequence is balanced if and only if the following condition holds:
\( \forall \text{prefix of } s, \; \#('(') \geq \#(')') \) and the total number of opening brackets is equal to the total number of closing brackets.
For example, the sequence (()())
is balanced while (()))(
is not.
inputFormat
The input is read from standard input and consists of two lines:
- The first line contains an integer \( n \) that denotes the length of the string.
- The second line contains the bracket sequence \( s \), a string of length \( n \) composed solely of the characters '(' and ')'.
outputFormat
Output a single line to standard output containing YES
if the string is balanced and NO
otherwise.
6
(()())
YES
</p>