#include <string>
#include <stack>
using namespace std;
int LongestValidParentheses(string& s)
{
int longest = 0;
int length = s.size();
stack<size_t> iStack;
stack<size_t> eStack;
stack<size_t> lStack;
int offset;
for (int i = 0; i < length; ++i)
{
if (s[i] == '(')
{
iStack.push(i);
}
else if (!iStack.empty())
{
size_t iLeft = iStack.top();
offset = i - iLeft + 1;
while(!eStack.empty() && iLeft < eStack.top())
{
eStack.pop();
lStack.pop();
}
if(!eStack.empty() && eStack.top() == iLeft-1)
{
offset += lStack.top();
eStack.top() = i;
lStack.top() = offset;
}
else
{
eStack.push(i);
lStack.push(offset);
}
if (offset > longest) longest = offset;
iStack.pop();
}
}
return longest;
}
#include <iostream>
#include <list>
#include <utility>
using namespace std;
int main(int argc, char** argv)
{
string parentheses1 = "()(()(())";
string parentheses2 = ")()())";
cout << LongestValidParentheses(parentheses1) << '\n';
cout << LongestValidParentheses(parentheses2) << '\n';
return 0;
}