32. Longest Valid Parentheses

本文探讨了如何寻找字符串中最长的有效括号子串的方法,提供了三种不同的算法实现:动态规划的基本思路、优化后的动态规划解决方案及栈的应用。通过具体示例详细解释了每种方法的思考过程和代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • Total Accepted: 87569
  • Total Submissions: 379765
  • Difficulty: Hard
  • Contributors: Admin

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

For "(()", the longest valid parentheses substring is "()", which has length = 2.

Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.




The naive thinking:

i -> j

if(i == '(' && j ==')')

dp[i][j] = dp[i - 1][j - 1] || (dp[i][k] && dp[k][j])

O(n3)

Stupid Code:

public class Solution {
    //dp[i][j]
    public int longestValidParentheses(String s) {
        boolean[][] dp = new boolean[s.length()][s.length() + 1];
        for(int i = 0 ; i < s.length(); i++){
            dp[i][i] = true;
        }
        int maxLen = 0;
        for(int l = 1; l <= s.length(); l++){
            for(int i = 0; i <= s.length() - l; i++){
                int j = i + l;
                if(l%2 == 0){
                    if(s.charAt(i) == '(' && s.charAt(j - 1) == ')'){
                        dp[i][j] = dp[i + 1][j - 1];
                        if(!dp[i][j]){
                            for(int k = i; k <= j ; k+=2){
                                if(dp[i][k] && dp[k][j]){
                                    dp[i][j] = true;
                                    break;
                                }
                            } 
                        }
                    } 
                    
                }
                if(dp[i][j]){
                    maxLen = Math.max(maxLen,l);
                }
            }
        }
        return maxLen;
    }
}

from https://discuss.leetcode.com/topic/35776/two-java-solutions-with-explanation-stack-dp-short-easy-to-understand/2

//DP solution 4ms
The idea is go through the string and use DP to store the longest valid parentheses at that point.
take example "()(())"
i : [0,1,2,3,4,5]
s : [( ,) ,( ,( ,) ,) ]
DP:[0,2,0,0,2,6]

1, We count all the ‘(‘.
2, If we find a ‘)’ and ‘(‘ counter is not 0, we have at least a valid result size of 2. “()"
3, Check the the one before (i - 1). If DP[i - 1] is not 0 means we have something like this “(())” . This will have DP “0024"
4, We might have something before "(())”. Take "()(())” example, Check the i = 1 because this might be a consecutive valid string.

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

// Stack solution 10ms
The idea is simple, we only update the result (max) when we find a "pair".
If we find a pair. We throw this pair away and see how big the gap is between current and previous invalid.
EX: "( )( )"
stack: -1, 0,
when we get to index 1 ")", the peek is "(" so we pop it out and see what's before "(".
In this example it's -1. So the gap is "current_index" - (-1) = 2.

The idea only update the result (max) when we find a "pair" and push -1 to stack first covered all edge cases.

public class Solution {
    public int longestValidParentheses(String s) {
        LinkedList<Integer> stack = new LinkedList<>();
        int result = 0;
        stack.push(-1);
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == ')' && stack.size() > 1 && s.charAt(stack.peek()) == '(') {
                stack.pop();
                result = Math.max(result, i - stack.peek());
            } else {
                stack.push(i);
            }
        }
        return result;
    }
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值