Leetcode, LongestValidParentheses
#include <iostream>
#include <stack>
#include <algorithm>
using namespace std;
//使用栈,时间复杂度O(n),空间复杂度O(n)
int solution(string s)
{
int max_len = 0, last = -1; //the position of the last ')'
stack<int> lefts;
for ( int i = 0; i < s.size(); ++i )
{
if ( s[i] == '(' )
{
lefts.push(i);
}
else
{
if (lefts.empty())
{
//no matching left
last = i;
}
else
{
//find a matching pair
lefts.pop();
if ( lefts.empty() )
{
max_len = max(max_len, i - last);
}
else
{
max_len = max(max_len, i - lefts.top());
}
}
}
}
return max_len;
}
int main()
{
cout << solution("(()") << endl; //2
cout << solution(")()())") << endl; //4
cout << solution("") << endl; //0
return 0;
}