#K91682. Valid Parentheses Sequence
Valid Parentheses Sequence
Valid Parentheses Sequence
You are given a string consisting solely of the characters '(' and ')'. Your task is to determine whether the parentheses sequence is valid. A valid sequence satisfies the following conditions:
- Every opening parenthesis '(' has a corresponding closing parenthesis ')'.
- A closing parenthesis ')' cannot appear before its matching opening parenthesis '('.
Mathematically, a parentheses sequence is valid if and only if for every prefix of the sequence, the number of '(' is greater than or equal to the number of ')', and in the entire sequence, the total counts are equal. In LaTeX format, one could express this condition as:
$$\forall k,\; 1\leq k \leq |s|, \quad \#( '(' ) \geq \#( ')' ) \quad \text{and} \quad \#( '(' ) = \#( ')' )$$
Determine and output "YES" if the sequence is valid, or "NO" otherwise.
inputFormat
The input consists of a single line containing the string s
which represents the parentheses sequence. The string is guaranteed to contain only the characters '(' and ')'.
Example:
(())()
outputFormat
Output a single line containing the string "YES" if the parentheses sequence is valid, or "NO" if it is invalid.
Example:
YES## sample
()
YES