#C12761. Longest Valid Parentheses
Longest Valid Parentheses
Longest Valid Parentheses
Given a string consisting only of the characters '(' and ')', determine the length of the longest well-formed (i.e., valid) parentheses substring.
A substring is considered valid if every opening parenthesis '\(' has a corresponding closing parenthesis '\)' and the pairs are properly nested. In other words, the substring must satisfy the rules of balanced parentheses.
For example, if the input is (()
, the longest valid substring is ()
with a length of 2.
Note: When a mathematical formula is necessary, please use LaTeX format. For this problem, if needed, the length calculation can be thought of as \(i - j\), where \(i\) and \(j\) are indices in the string.
inputFormat
The input consists of a single line containing a string composed solely of the characters '(' and ')'.
outputFormat
The output is a single integer representing the length of the longest valid (well-formed) parentheses substring.
## sample(()
2