longest valid bracket (java)

Question : Given a string containing only '('and ')', find the length of the longest valid (correctly formatted and continuous) bracket substring.
(()) , ()() both cases represent a match

Problem-solving ideas : When using dynamic programming, the following situations need to be considered:

  • The dp value of the character ' ( ' must be 0

    As for ')', we need to discuss it on a case-by-case basis: because we are discussing the case of s[i-1], i needs to start from 1.

  • When s[i-1]==' ( ', dp[i]=dp[i-2]+2;//But what needs to be noted here is that if i equals 1, that is, when '()', i-2 is out of bounds, so i must be greater than or equal to 2. When it is greater than 2, the transfer equation is: dp[i] = dp[i-2]+2, otherwise dp[i]=2, corresponding to () a situation;

  • When s[i-1]==' ) ', the situation is a bit complicated. First, it must be judged that i-dp[i-1]>0, that is, there is something that can match it, s[i-dp[i -1]-1] is '(', otherwise dp[i] is 0.

  • Then judge whether i-dp[i-1] is greater than 2. If it is greater than 2, it means that there is something like ()(()()) before it. If it is less than 2, it means (()()). In the former case, dp[ i]=dp[i-1]+dp[i-dp[i-1]-2] +2, in the latter case dp[i]=dp[i-1]+2;

  • Just take the maximum value of dp during the loop judgment process.

code show as below:

class Solution {
    
    
    public int longestValidParentheses(String s) {
    
    
        int length=s.length();
        int [] dp=new int[length];
        char[] list=s.toCharArray();
        int rs=0;
        for(int i=1;i<length;i++){
    
    
            if(list[i]==')'){
    
    
                if(list[i-1]=='('){
    
    
                  dp[i]= (i>=2 ? dp[i-2]:0) +2;
                }else if(i-dp[i-1]>0&&list[i-dp[i-1]-1]=='('){
    
    
                  dp[i]=dp[i-1]+(i-dp[i-1]>=2?dp[i-dp[i-1]-2]:0)+2;
                }
            }
            rs=Math.max(rs,dp[i]);
        }
        return rs;
    }
}

Guess you like

Origin blog.csdn.net/yang12332123321/article/details/127961342