【LeetCode】32. 最长有效括号(DP)

题目

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

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

解法1:暴力,一路扫过去,遇到'('就++,')'就--,最后判断count是否为0,效率很低

class Solution {
    public int longestValidParentheses(String s) {
        int count = 0;
        int max = 0;
        for(int i = 0; i < s.length(); i++){
            count = 0;
            for(int j = i; j < s.length(); j++){
              if(s.charAt(j) == '('){
                  count++;
              }else{
                  count--;
              }
              if(count < 0) break;
              if(count == 0){
                  if(j - i + 1 > max){
                      max = j - i + 1;
                  }
              }
            }
        }
        return max;
    }
}

解法2: 动态规划

class Solution {
    public int longestValidParentheses(String s) {
        int maxans = 0;
        int len = s.length();
        int[] dp = new int[len];
        for(int i = 1; i < len; i++){
            if(s.charAt(i) == ')'){
                if(s.charAt(i - 1) == '('){
                    dp[i] = (i >= 2 ? dp[i - 2] : 0) + 2;
                }else if(i - dp[i - 1] > 0 && s.charAt(i - dp[i - 1] - 1) == '('){
                    dp[i] = dp[i - 1] + ((i - dp[i - 1]) >= 2 ? dp[i - dp[i - 1] - 2] : 0) + 2;
                }
                maxans = Math.max(maxans, dp[i]);
            }
        }
        return maxans;
       
    }
}
原文地址:https://www.cnblogs.com/whisperbb/p/12657195.html