public int longestValidParentheses2(String s) {
        char[] str = s.toCharArray();
        int[] dp = new int[str.length];
        int maxLen = 0;
        for (int i = 1; i < str.length; ++i) {
            int j = i - dp[i - 1] - 1;
            if (str[i] == ')' && j >= 0 && str[j] == '(') {
                dp[i] = 2 + dp[i - 1] + (j >= 1 ? dp[j - 1] : 0);
            }
            maxLen = Math.max(maxLen, dp[i]);
        }
        return maxLen;
    }