# 最长有效括号

给你一个只包含 '(' 和 ')' 的字符串,找出最长有效(格式正确且连续)括号子串的长度。

 

示例 1:

输入:s = "(()"
输出:
2
解释:
最长有效括号子串是 "()"

示例 2:

输入:s = ")()())"
输出:
4
解释:
最长有效括号子串是 "()()"

示例 3:

输入:s = ""
输出:
0

 

提示:

## template ```java import java.util.*; class Solution { public int longestValidParentheses(String s) { int left = 0, right = 0, max = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '(') left++; else right++; if (left == right) max = Math.max(max, left * 2); if (right > left) left = right = 0; } left = 0; right = 0; for (int i = s.length() - 1; i >= 0; i--) { if (s.charAt(i) == '(') left++; else right++; if (left == right) max = Math.max(max, left * 2); if (right < left) left = right = 0; } return max; } } ``` ## 答案 ```java ``` ## 选项 ### A ```java ``` ### B ```java ``` ### C ```java ```