码迷,mamicode.com
首页 > 其他好文 > 详细

Longest Valid Parentheses

时间:2015-04-02 11:40:03      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:dp

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.

int longestValidParentheses(string s) {
	if (s.empty())
		return 0;
	int max =0;
	vector<int>Maxlength(s.size(),0);
	for (int i = Maxlength.size()-2;i>=0;--i)
	{
		if (s[i]=='(')
		{
			int j = i+1+Maxlength[i+1];
			if (j<s.size()&&s[j]==')')
			{
				Maxlength[i] = Maxlength[i+1]+2;
				if (j+1<s.size())
					Maxlength[i]+=Maxlength[j+1];
			}
		}
		max =max<=Maxlength[i]?Maxlength[i]:max;
	}
	return max;
}

 

int longestValidParentheses(string s) {
	if (s.empty())
		return 0;
	stack<int>CharStack;
	CharStack.push(-1);
	int length =0;
	int longestlength =0;
	for (int i = 0;i!=s.size();++i)
	{
		if (s[i]=='(')
			CharStack.push(i);
		else if (s[i]==')')
		{
			if (CharStack.size()>1)
			{
				CharStack.pop();
				length=i-CharStack.top();
				longestlength =max(longestlength,length);
				
			}
			else{
				CharStack.pop();
				CharStack.push(i);
			}
		}
	}
	return longestlength;
}



 

Longest Valid Parentheses

标签:dp

原文地址:http://blog.csdn.net/li_chihang/article/details/44829041

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!