【Leetcode】之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.

二.我的解题思路

拿到这个题目,我的思路比较naive。就是在每个(位置都要去找所能匹配的最长子串,但是这样做的时间复杂度比较高。之后参考了网上的资料,转变思路。针对括号匹配这一问题的特殊性,可以尝试去遍历一次字符串,记录下匹配的子串的长度,再取最大值。参考博客http://blog.youkuaiyun.com/zhangwei1120112119/article/details/16812679
程序如下:

class Solution
{
public:
    int longestValidParentheses(string s)
    {
        stack<int>S;
        S.push(-1);
        int ans=0;
        for(string::size_type i=0;i<s.size();i++)
        {
            //printf("%d\n",S.size());
            char ch=s[i];
            if(ch == '(')
            {
                S.push(i);
            }
            else
            {
                if(S.size()>1)
                {
                    S.pop();
                    int tmp=S.top();
                    ans=max(ans,(int)i-tmp);
                }
                else
                {
                    S.pop();
                    S.push(i);
                }
            }
        }
        return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值