1. 程式人生 > 實用技巧 >32. 最長有效括號 Longest Valid Parentheses

32. 最長有效括號 Longest Valid Parentheses

Given a string containing just the characters'('and')', find the length of the longest valid (well-formed) parentheses substring.

Input: s = "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()".

方法一:

動態規劃

如果最右為‘(’,放棄

如果最右為‘)’,

如果i-1為‘(’, dp[i] = dp[i-2] +2

如果i-1為‘)’,且i-dp[i-1]-1 為'(',dp[i]=dp[i-1]+dp[i-dp[i-1]-2] +2

public int longestValidParentheses(String s) {
        int maxans = 0;
        int [] dp = new int[s.length()];
        for(int i = 1; i < s.length(); i++){
            if(s.charAt(i) == ')'){
                if(s.charAt(i - 1) == '('){
                    dp[i] = i >= 2 ? (dp[i - 2] + 2) : 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://leetcode.com/problems/longest-valid-parentheses/

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