public class Solution {
    public int longestValidParentheses(String s) {
        if(s==null || s.length()<1) return 0;
        int max = 0;
        int left = -1;
        Stack<Integer> sta = new Stack<Integer>();
        for(int i = 0 ; i < s.length(); i++){
            if(s.charAt(i)=='('){
                sta.push(i);
            }else{
                if(sta.isEmpty()) left = i;
                else{
                    sta.pop();
                    if(sta.isEmpty()) max=Math.max(max,i-left);
                    else max=Math.max(max,i-sta.peek());
                }
            }
        }
        return max;
    }
}
