Loading problem...
Given a string s composed exclusively of opening brackets '(' and closing brackets ')', your task is to determine the length of the longest contiguous substring that forms a properly balanced (well-formed) bracket sequence.
A balanced bracket sequence follows these rules:
'(' must have a corresponding closing bracket ')' that appears later in the sequence.')' must have a corresponding opening bracket '(' that appears earlier in the sequence.The substring must be contiguous (consecutive characters from the original string), and you are searching for the maximum length among all such valid substrings. If no balanced substring exists, return 0.
s = "(()"2The input string "(()" contains three characters. While the entire string is not balanced (there's an unmatched opening bracket at the start), the substring "()" starting at index 1 forms a valid balanced sequence. This substring has length 2, which is the maximum achievable.
s = ")()())"4The input ")()())" has several portions to analyze. The first character ')' cannot start any valid sequence. However, the substring "()()" spanning indices 1 through 4 is perfectly balanced—each opening bracket has a matching closing bracket in proper order. This gives us a length of 4, which is the longest balanced substring in this input.
s = ""0An empty string contains no characters at all, so there cannot be any balanced bracket sequence. The answer is 0.
Constraints