32. Longest Valid Parentheses

本文介绍了两种解决最长有效括号子串问题的方法:一种使用栈结构,通过记录合法子串的位置来找到最长的有效括号子串;另一种采用动态规划方式,通过状态转移方程计算最长有效括号子串的长度。

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

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. 

主题思想: 关于这种匹配的,一般用栈结构,所以第一种解法是利用栈结构,这道题某种意思上和求最长连续子序列有点像,因为是求最大子字符串长度,所以只要记录合法的字串其实位置就可以了。

思路: 遇见合法的对,就出栈,并计算更新最大长度,
其他情况入栈,
具体代码:

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

    Stack<Integer> stack = new Stack<>();
    for(int i = 0; i < s.length(); i++){

        if(s.charAt(i) == ')' && !stack.empty() && s.charAt(stack.peek())== '(')
        {
            stack.pop();

            if(stack.empty()) max=Math.max(max,i+1);
            else  max=Math.max(max,i-stack.peek());
        }

        else{

            stack.push(i);
        }
    }
    return  max;
}
}

第二种解法 动态规划: 这道题也是一道动态规划题,
所以脑子里应该有意思到这是一道dp题,
状态转移方程,

如果遇见合法对
dp[i]=2+dp[i-1];
然后判断 i-dp[i] 是否下标合法,如果合法
dp[i]=dp[i]+dp[i-dp[i]];

具体代码:

public class Solution {
    public int longestValidParentheses(String s) {
        int mx=0;
        if(s==null||s.length()<2) return 0;

        int n=s.length();
        int [] dp=new int[n];

        for(int i=0;i<n;i++) dp[i]=0;
        int open=0;
        for(int i=0;i<s.length();i++){
            if(s.charAt(i)=='(') open++;
            else if(s.charAt(i)==')'&&open>0){
                dp[i]=2+dp[i-1];
                if(i-dp[i]>0) dp[i]+=dp[i-dp[i]];

                open--;

            }
            if(dp[i]>mx) mx=dp[i];
        }
        return mx;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值