32. Longest Valid Parentheses

Description

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

DP, time O(n), space O(n)

用dp[i]表示s.substring(0, i)的LVP,那么:

  • if s[i - 1] == '(': dp[i] = 0;
  • else
    • if s[i - 2] == '(': dp[i] = dp[i - 2] + 2; // eg: (())()
    • else: dp[i] = dp[i - 1] + dp[i - dp[i - 1] - 2] + 2; // eg: ()(())

千万别忘记往前面匹配到j之后还要试着跟s.substring(0, j)做连接!

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

你可能感兴趣的:(32. Longest Valid Parentheses)