給定一個只包含 '('
和 ')'
的字符串,找出最長的包含有效括號的子串的長度。
示例 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;
}
}