> 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)
{
stack<int> left;
int result = 0;
int last = -1;
for(int i = 0; i < s.length(); i++)
{
if(s[i] == '(')
left.push(i);
else//')'
{
if(left.empty())
last = i;
else
{
left.pop();
int len = 0;
if(left.empty())
len = i - last;
else
len = i - left.top();
result = std::max(result, len);
}
}
}
return result;
}