public static int longestValidParentheses (String s) {//AC
    	if (s == null || s.length() < 2) return 0;
    	int maxlen = 0;
    	int last = -1;
    	int i = 0;
    	Stack<Integer> stk = new Stack<Integer>();
    	while (i < s.length()) {
    		char curr = s.charAt(i);
    		if (curr == '(') {
    			stk.push(i);
    		}
    		else {
    			
    			if (stk.isEmpty()) {
    				last = i;
    			}
    			else {
    				stk.pop();
    				if (stk.isEmpty()) {
    					maxlen = Math.max(maxlen, i - last);
    				}
    				else {
        				maxlen = Math.max(maxlen, i - stk.peek());
    				}
    			}
    		}
    		++i;
    	}
    	return maxlen;
    }