leetcode 32:Longest Valid Parentheses

题目:

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来存储每个单括号对应的有效括号个数,则有下面的关系:


事件复杂度:O(n)


class Solution
{
public:
	int longestValidParentheses(string s)
	{
		int size=s.size();
		if(size<2) return 0;
		int left=0,max=0;
		vector<int> DP(size,0);
		for(int i=0;i<size;i++)
		{
			if(s[i]=='(')		left++;
			else if(left>0) 
			{
				left--;
				if(s[i-1]=='(')
					DP[i]=((i-2)>0?DP[i-2]+2:2);
				else if(s[i-1]==')'&&s[i-DP[i-1]-1]=='(')
					DP[i]=DP[i-1]+2+((i-DP[i-1]-2)>=0?DP[i-DP[i-1]-2]:0);
			}
			if(DP[i]>max) max=DP[i];
		}
		return max;
	}
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值