[Leetcode] #32 Longest Valid Parentheses

本文探讨了LeetCode平台的变化,从按年份排列改为了数字序列,并分享了一次成功优化算法运行时间的经历,从800ms降至300ms。通过引入intleft替代栈,改进了括号匹配算法,实现了效率提升。

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

最近发现Leetcode变化不少,取消了按年份排列,变成了数字序列。另外免费的试题都是网友提供的了,另有10道题需要收费才能做。

打开这个题目,发现原来提交的代码运行时间800多ms,应该是算法本身有问题。于是重写了一下,变成300多ms啦。

思路是用int left代替栈了,只要知道左括号的个数就行了。当匹配一个右括号后,不仅要看包含的括号个数,还要判断紧挨着的括号是不是完整的。

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值