public int longestValidParentheses(String s) {
        int maxLen = 0;
        Stack<Integer> stack = new Stack<Integer>();
        char[] str = s.toCharArray();
        for (int i = 0; i < str.length; ++i) {
            // Current ')' is a match
            if (str[i] == ')' && !stack.isEmpty() && str[stack.peek()] == '(') {
                stack.pop();
                if (stack.isEmpty()) {
                    maxLen = i + 1;
                } else {
                    maxLen = Math.max(maxLen, i - stack.peek());
                }
            // Current '(' or ')' is not a match, push it to stack
            } else {
                stack.push(i);
            }
        }
        return maxLen;
    }