Java concise DP solution


  • 0
    A
    public class Solution {
        public int longestValidParentheses(String s) {
            int[] dp = new int[s.length()+1];
            int res = 0;
            for (int i=1; i<s.length(); i++) {
                if (s.charAt(i) == ')' && i-dp[i] >= 1 && s.charAt(i-dp[i]-1) == '(') {
                    dp[i+1] = dp[i-dp[i]-1] + dp[i] + 2;
                    res = Math.max(res, dp[i+1]);
                }
            }
            return res;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.