[LeetCode]032. Longest Valid Parentheses

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

For "(()", the longest valid parentheses substring is "()", which has length = 2.

Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.

Solution: use the dp, create a int[] dp to store the longest valid parentheses.

dp[i] represents the longest valid parentheses from i to the end(len-1);

watch the annotations.

running time: O(n)

Memory:O(n).


public class Solution {
    public int longestValidParentheses(String s) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int len = s.length();
        if(s==null || len==0){
            return 0;
        }
        int[] dp = new int[len+1];
        int max = 0;
        for(int i=len-2; i>=0; i--){
            if(s.charAt(i) == '('){
                int j = i+1+dp[i+1];
                if(j<len && s.charAt(j)==')'){
                    dp[i] = 2+dp[i+1]+dp[j+1];
                    //2+dp[i+1] represents the valid parentheses from i to j
                    //and must add dp[j+1];
                }
            }
            max = Math.max(max, dp[i]);
        }
        return max;
    }
}


你可能感兴趣的:(LeetCode,dp)