#C2362. Longest Balanced Parentheses Substring
Longest Balanced Parentheses Substring
Longest Balanced Parentheses Substring
Given a string s
consisting only of the characters '(' and ')', your task is to determine the length of the longest contiguous substring that is a valid (well-formed) sequence of parentheses. A valid sequence means every opening parenthesis has a corresponding closing parenthesis in the correct order. One commonly used approach is to utilize a stack to keep track of indices, where the length for a valid segment can be computed using the formula \(\text{length} = i - \text{stack.top()}\) at each step.
For example:
s = "()"
yields2
.s = "(())"
yields4
.s = ")()())"
yields4
.
Implement an efficient solution that reads input from the standard input and writes the result to the standard output.
inputFormat
The input consists of a single line containing a string s
of parentheses. The string's length can vary, but it only contains the characters '(' and ')'.
outputFormat
Output a single integer representing the length of the longest valid (balanced) substring of parentheses.
## sample()
2