32. 最长有效括号

2019/01/21 00:04 上午 posted in  LeetCode

https://leetcode-cn.com/problems/longest-valid-parentheses/description/

给定一个只包含 '(' 和 ')' 的字符串,找出最长的包含有效括号的子串的长度。

示例 1:

输入: "(()"
输出: 2
解释: 最长有效括号子串为 "()"
示例 2:

输入: ")()())"
输出: 4
解释: 最长有效括号子串为 "()()"

代码:

public int longestValidParentheses(String s) {
    int[] dp = new int[s.length()];
    int max = 0;
    for (int i = 1; i < s.length(); i++){
        if (s.charAt(i) == '('){
            dp[i] = 0;
        }else{
            if (dp[i - 1] != 0) {
                int index = i - dp[i - 1] - 1;
                if (index >= 0 && s.charAt(index) == '(') {
                    dp[i] = dp[i - 1] + 2;
                    if (index - 1 >= 0 ){
                        dp[i] += dp[index - 1];
                    }
                }
            }
            if (s.charAt(i - 1) == '('){
                if (i >= 2) {
                    dp[i] = dp[i] > dp[i - 2] + 2 ? dp[i] : dp[i - 2] + 2;
                }else{
                    dp[i] = 2;
                }
            }
            if (max < dp[i]){
                max = dp[i];
            }
        }
    }
    return max;
}