leetcode 32.最长有效括号
左神 中级提升班 3-2
class Solution { public int f(String s) { //1 char[] chs = s.toCharArray(); int n = s.length(); //表示以i结尾的最长有效子串 int[] dp = new int[n]; dp[0] = 0; //2 for (int i = 1; i < n; i++) { //analyse chs[i] if (chs[i] == '(') { dp[i] = 0; } else { if (i - dp[i - 1] - 1 >= 0 && chs[i - dp[i - 1] - 1] == '(') { dp[i] = dp[i - 1] + ((i - dp[i - 1] - 2 >= 0) ? dp[i - dp[i - 1] - 2] : 0) + 2; } } } int ans = -1; for (int i = 0; i < n; i++) { ans = Math.max(ans, dp[i]); } return ans; } }