LeetCode Longest Valid Parentheses

本文详细解读了如何通过栈结构解决计算给定字符串中连续配对成功的括号子串长度的问题,并提供了Java代码实现,旨在帮助读者理解和掌握相关算法逻辑。

摘要生成于 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.

题意:

给定一串字符,计算其中连续配对成功的字符串的长度。

题解:

此题一开始我的理解有问题,以为是要求在这个字符串中的所有能够匹配的字符串的个数;所以屡次试验都有问题,然后仔细读题发现,其实是要求连续的一段匹配的字符串的长度,比如"()(()",它返回的长度其实是2,而不是4。所以,在求相应的长度的时候,需要记录"("出现的位置,然后计算匹配的长度,如果匹配的长度大于之前记录的长度,那么久更新,否则就不变。

public class Solution 
{
    public static int longestValidParentheses(String s) 
    {
        if (s == null || s.length() == 0)
            return 0;
        int len = s.length(), maxLen = 0;
        Stack<Integer> stack = new Stack<>();
        stack.push(-1);
        for (int i = 0; i < len; i++) 
        {
            if (s.charAt(i) == '(')
                stack.push(i);
            else 
            {
                if (stack.size() > 1 && s.charAt(stack.peek()) == '(') 
                {
                    stack.pop();
                    System.out.println(stack.peek());
                    maxLen = Integer.max(i - stack.peek(), maxLen);
                    System.out.println(maxLen);
                } 
                else 
                    stack.push(i);
            }
        }
        return maxLen;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值