leetcode Longest Valid Parentheses

Longest Valid Parentheses

 Total Accepted: 4153 Total Submissions: 22587My Submissions

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.


每次操作栈和其他容器的时候都要注意是否为空。

这道题的计算要注意,如何才能得到当前最长valid parentheses。

int longestValidParentheses(string s) 
	{
		stack<int> stk;
		int len = 0;

		for (int i = 0; i < s.length(); i++)
		{
			if (s[i] == ‘(‘) stk.push(i);
			else
			{
				if (stk.empty()) stk.push(i);
				else
				{
					if (s[stk.top()] == ‘(‘)
					{
						stk.pop();
						if (stk.empty()) len = max(len, i+1);
						else len = max(len, i-stk.top());
					}
					else stk.push(i);
				}
			}
		}
		return len;
	}




leetcode Longest Valid Parentheses

上一篇:[转]:测试用例的设计方法(全)


下一篇:subversion(SVN)常规使用