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.

我的代码:

class Solution {
public:
	int longestValidParentheses(string s) 
	{
		for (int i = 0; i < s.length(); ++i)
		{
			if (')' == s[i])
				for (int j = i-1; j >= 0; j--)
				{
					if ('*' == s[j])
						continue;
					if (')' == s[j])
						break;
					if ('(' == s[j])
					{
						s[j] = '*';
						s[i] = '*';
						break;
					}
				}
		}
		int maxv = 0;
		int cur = 0;
		for (int i = 0; i < s.length(); ++i)
		{
			if ('*' == s[i])
				cur++;
			else if ('(' == s[i] || ')' == s[i])
			{
				maxv = max(maxv, cur);
				cur = 0;
			}
		}
		return max(maxv, cur);
	}
};

拷别人用堆栈的代码:

class Solution {
public:
    int longestValidParentheses(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        stack<int> pStack;
        int lastleft=0;//keep track of the start point of the current longest valid parenthese
        int longest=0;
        for(int i=0;i<s.length();i++)
        {
            if(s[i]=='(')
            {
                pStack.push(i);
            }
            else
            {
                if(!pStack.empty())
                {
                    pStack.pop();
                    //now pStack.top() the previous index of the start point of the longest valid parenthese
                    if(!pStack.empty())
                        longest=max(longest,i-pStack.top());
                    else
                        longest=max(longest,i-lastleft+1);
                }
                else{
                    //mismatched ) found, the longest string must end
                    //update the start of the first valid parenthtes 
                    lastleft=i+1;
                }
            }
        }
        return longest;
    }
};





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值