LeetCode 32.Longest Valid Parentheses【Java】

本文深入探讨了如何解决最长有效括号问题,提供了一种使用前缀和的方法,并通过两个方向的遍历来获取最大长度的有效括号序列。同时,文章还介绍了一种基于堆栈的解决方案,通过维护一个堆栈来跟踪括号的有效性,从而找到最长的有效括号子串。

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

题目描述

32. 最长有效括号

AC代码
/*
括号序列合法<=>所有前缀和>=0,且总和等于0
(())
1 1 -1 -1
start 当前枚举的这一端的开头
cnt 前缀和
cnt<0 那么 start=i,cnt=0
cnt>0 那么 继续做
cnt==0 那么 [start,i]时合法的括号序列
*/

class Solution {
    public int longestValidParentheses(String s) {
        int res=work(s);
        System.out.println(res);
        s=new StringBuilder(s).reverse().toString();
        char[] ch=s.toCharArray();
        //(和)的ascii码可以发现一个是28一个是29,差别在于最后一位不同,可以通过^改变.
        for(int i=0;i<ch.length;i++)
            ch[i]^=1;
        s=new String(ch);
        return Math.max(res,work(s));
    }


    public int work(String s){
        int res=0;
        for(int i=0,start=0,cnt=0;i<s.length();i++){
            if(s.charAt(i)=='(')
                cnt++;
            else
            {
                cnt--;
                if(cnt<0){
                    start=i+1;cnt=0;
                }else
                {
                    if(cnt==0) res=Math.max(res,i-start+1);
                } 
            }
        }
        return res;

    }
}

通过堆栈来解题。

class Solution {
    public int longestValidParentheses(String s) {
        assert s != null;
        if (s.length() < 2) {
            return 0;
        }
        Stack<Integer> stack = new Stack<>();
        int max = 0;

        stack.add(-1);

        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '(') {
                stack.push(i);
            } else {
                stack.pop();
                if (stack.isEmpty()) {
                    stack.push(i);
                } else {
                    max = max > (i - stack.peek()) ? max : (i - stack.peek());
                }

            }

        }
        return max;

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值