Longest Valid Parentheses

29 篇文章 0 订阅

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.



dp[i] 记录下标i 与其左边的串,往左能匹配的最大长度;

用栈记录(,遇到)则出栈,匹配出来的最大连续的串,一定是最唯一的也是最长的串!

dp[i] = stack.empty()? 0 :i - stack.top + 1 + dp[top - 1];stack为未匹配的(的栈,遇到(即入栈,遇到)出栈,

若栈空则dp[i] = 0即当前下标能往左匹配的最大连续长度为0,这里要注意若果top == 0 则dp[i] = i - stack.top + 1 +0;

因为0往左为空串,空串能匹配的长度肯定为0!



class Solution {
public:
    int longestValidParentheses(string s) {
        if(!s.size())return 0;
		stack<int> stc;
		int len = s.size();
		int *dp = new int[len];
		
		int rst = 0;
		//对于括号匹配,用栈保存( 匹配,能获得的匹配结果,是唯一的连续的也是最长的能匹配的结果
		for(int i = 0; i < len; i++)
		{
			if(s[i] == '(')
			{
				stc.push(i);
				dp[i] = 0;
				continue;
			}
			if(!stc.empty())
			{
				int idx = stc.top();
				stc.pop();
				//当前匹配的左括号所在位置的左边最大匹配,加上当前匹配的左括号的长度
				dp[i] = i - idx + 1 + (idx == 0 ? 0 :dp[idx - 1]);
			}
			else
				dp[i] = 0;

			rst = max(rst, dp[i]);
		}
		return rst;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值