public static int longestValidParentheses(String s) { if (s==null||s.length()==0) { return 0; } int len = s.length(); int[] countLeft = new int[len]; int left = 0; for (int i = 0; i < len; i++) { if (s.charAt(i) == '(') { left++; countLeft[i] = -1; //不用 } else { if (left > 0) { countLeft[i] = left; left--; } else { left = 0; countLeft[i] = left; } } }
int[] dp = new int[len+1]; int max = Integer.MIN_VALUE; boolean isStart = false; dp[0] = 0; for (int i = 1; i < dp.length; i++) { if (!isStart) { if (s.charAt(i-1)== '(') { dp[i] = dp[i-1]; } else { if (countLeft[i-1] > 0) { dp[i] = dp[i-1]+2; } else { dp[i] = dp[i-1]; isStart = true; } } } else { dp[i] = 0; isStart = false; } max = Math.max(dp[i], max); } return max; }