import java.util.*;


public class Solution {
    /**
     * 
     * @param s string字符串 
     * @return int整型
     */
    public int longestValidParentheses (String s) {
        // write code here
        if (s == null || s.length() < 2) {
            return 0;
        }
        char[] arr = s.toCharArray();
        int n = arr.length;
        int[] dp = new int[n];
        int max = 0;
        for (int i = 1; i < n; i++) {
            if (arr[i] == ')') {
                if (arr[i - 1] == '(') {
                    dp[i] = (i >= 2 ? dp[i - 2] : 0) + 2;
                } else if (i - dp[i - 1] > 0 && arr[i - dp[i - 1] - 1] == '(') {
                    dp[i] = (i - dp[i - 1] > 1 ? dp[i - dp[i - 1] - 2] : 0) + dp[i - 1] + 2;
                }
            }
            max = Math.max(max, dp[i]);
        }
        return max;
    }

    private boolean isValid(char[] arr, int l, int r) {
        Stack<Character> stack = new Stack<>();
        while (l <= r) {
            if (!stack.isEmpty() && stack.peek() == '(' && arr[l] == ')') {
                stack.pop();
            } else {
                stack.push(arr[l]);
            }
            l++;
        }
        return stack.isEmpty();
    }
}