longestValidParentheses-the longest valid parentheses.

Title:

Given a string containing only'(' and')', find the length of the longest substring containing valid parentheses.

Example 1:

Input: "(()"
Output: 2
Explanation: The longest valid bracket substring is "()"

Example 2:

Input: “)()())”
Output: 4
Explanation: The longest valid bracket substring is “()()”

Related Topics string dynamic programming

Problem-solving ideas

1. Set up an array, which stores the maximum value of the corresponding position () of each character in the
string 2. Determine the maximum value of the current position of the string, mainly depending on two situations
2.1 One ending with ()
depends on the current situation The first two positions of the position, the state of the character. Accumulate 2 to be
2.2 A kind ending with )), but it can form (((()))) this kind of string. In
this case, the state of accumulating the second to last), and conforming to (((())) ) The transition of () before the string can be accumulated on the basis of 2.1.

Code:

class Solution {
    public int longestValidParentheses(String s) {
           int res=0;

           //用来记录字符串中每个字符对应位置()的最大值
           int[] dp=new int[s.length()];
        for (int i = 1; i < s.length(); i++) {
            if(s.charAt(i)==')')
            {
                //步骤2.1()结尾的
                if(s.charAt(i-1)=='(')
                    dp[i]=  (i>=2 ? dp[i-2] : 0) +2;
                //以))结尾的,需要找到对应的(,以及判断之前是否有)并判断状态数值大小
                else if(i-dp[i-1]-1>=0&&s.charAt(i-dp[i-1]-1)=='(')
                    dp[i]=dp[i-1]+( i-dp[i-1]-2>=0 ? dp[i-dp[i-1]-2] : 0)+2;
                res=Math.max(res,dp[i]);
            }
        }
        return res;
    }
}

effect

The info
answer was successful:
execution time: 2 ms, defeating 74.72% of Java users
Memory consumption: 38.3 MB, defeating 83.68% of Java users

Guess you like

Origin blog.csdn.net/tangshuai96/article/details/111401613