import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return int整型
*/
public int longestValidParentheses (String s) {
// write code here
if(s == null || s.length() == 0) return 0;
Stack<Integer> stack = new Stack<>();
//压入-1作为哨兵,1 - (-1) = 2
stack.push(-1);
int maxLength = 0;
for(int i = 0;i<s.length();i++){
int c = s.charAt(i);
if(c == '(')
stack.push(i);
else
stack.pop();
if(stack.isEmpty()){
stack.push(i);//作为新边界
}
else
maxLength = Math.max(maxLength, i - stack.peek());
}
return maxLength;
}
}