首页 > 其他 > 详细

Longest Valid Parentheses

时间:2015-04-02 11:39:05      阅读:181      评论:0      收藏: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.

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!