给定一个只包含 '('
和 ')'
的字符串,找出最长的包含有效括号的子串的长度。
示例 1:
输入: "(()"
输出: 2
解释: 最长有效括号子串为 "()"
示例 2:
输入: ")()())
" 输出: 4 解释: 最长有效括号子串为"()()"
class Solution {
public int longestValidParentheses(String s) {
char[] chars = s.toCharArray();
int idx = 1,res=0;
int[] stack = new int[chars.length+1];
for (int i = 0;i<chars.length;i++) {
if (chars[i]=='('){
stack[idx++]=i;
}else {
if (idx==1){
stack[0] = i+1;
}else {
idx--;
res = idx==1?Math.max(res,i-stack[0]+1):Math.max(res,i-stack[idx-1]);
}
}
}
return res;
}
}