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