#C11628. Longest Balanced Parentheses
Longest Balanced Parentheses
Longest Balanced Parentheses
You are given a string s
consisting only of the characters '(' and ')'. Your task is to determine the length of the longest substring that forms a balanced parentheses sequence.
A balanced parentheses sequence is defined recursively as follows:
- An empty string is balanced.
- If S is balanced, then
(S)
is balanced. - If S and T are balanced, then their concatenation
ST
is balanced.
If no balanced substring exists, the answer should be 0.
You may use the following mathematical expression for balanced sequences: \( \text{if } S \text{ is balanced, then } (S) \text{ is balanced} \).
inputFormat
The input consists of a single string s
provided via standard input. The string contains only the characters '(' and ')'.
Example Input:
()()
outputFormat
Output the length of the longest balanced parentheses substring. The output should be printed to standard output.
Example Output:
4## sample
()
2