#K5256. Longest Balanced Parentheses Substring
Longest Balanced Parentheses Substring
Longest Balanced Parentheses Substring
Given a string S consisting solely of the characters (
and )
, your task is to determine the length of the longest contiguous substring that forms a valid (i.e., balanced) parentheses sequence.
A valid sequence is defined as one in which every opening parenthesis (
is matched with a corresponding closing parenthesis )
, and the pairs are properly nested. For instance, the substring "((()))
" is perfectly balanced with a length of 6, while "<code())</code>" has a maximum balanced length of 2.
You may find it useful to consider the formula \( \text{length} = i - j \), where \( j \) denotes the index of the last unmatched parenthesis before a balanced substring starting right after it.
Read the input from stdin and output your answer to stdout.
inputFormat
A single line containing the string S composed only of the characters '(' and ')'.
outputFormat
A single integer representing the length of the longest balanced parentheses substring.## sample
(()))
4