#K12861. Valid Parentheses by Deleting One Character
Valid Parentheses by Deleting One Character
Valid Parentheses by Deleting One Character
You are given a string s
consisting of lowercase English letters and parentheses (' and ')'
. Your task is to determine whether it is possible to obtain a valid string by deleting at most one character from s
.
A string is considered valid if the parentheses in the string are balanced. In other words, every opening parenthesis (
must have a corresponding closing parenthesis )
in the correct order.
The validation can be mathematically described by the following condition: if we process the string from left to right while increasing a counter for every (
and decreasing it for every )
, then the counter should never be negative and must be zero after processing the entire string. This can be represented in LaTeX as:
$$\forall i,\; count_i \ge 0 \quad \text{and} \quad count_{\text{end}} = 0.$$
If the original string is already valid, the answer is YES
. Otherwise, check if removing exactly one character makes it valid. If so, print YES
; otherwise, print NO
.
inputFormat
The input consists of a single line containing the string s
.
Note: The string may contain lowercase letters and the characters '(' and ')'.
outputFormat
Output a single line: YES
if it is possible to obtain a valid string by deleting at most one character; otherwise, output NO
.
a(b)c)
YES
</p>