public int longestValidParentheses(String s) {
Stack<Integer> stack = new Stack<>();
int max = 0;
//初始化有效括号的起始值,例如(),1-(-1)=2,有效括号长度为2
int left = -1;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
stack.push(i);
} else {
//如果只有),前面没有(的话,有效括号就从i记起
if (stack.isEmpty()) {
left = i;
} else {
//弹出与)对应的(
stack.pop();
if (stack.isEmpty()) {
max = Math.max(max, i - left);
} else {
max = Math.max(max, i - stack.peek());
}
}
}
}
return max;
}