#include <string>
#include <vector>
#include <iostream>
using namespace std;
/*
Given a string containing just the character '(' and ')', find the length of the longest
valid parentheses substring.
for "(()", the longest valid parentheses substring is "()" which has length 2.
Another example ")()())", where the longest valid parentheses substring is "()()", which
has length 4.
*/
// Use one pointer always points to the end index of vector.
int longestValidParentheses(string s) {
if(s.size() <= 1) return 0;
vector<int> index;
int maxSize = 0;
for(int i = 0; i < s.size(); ++i) {
if(s[i] == '(') {
index.push_back(i); // push the index number.
} else {
if(!index.empty() && s[index.back()] == '(') {
index.pop_back();
int lastPos = -1;
if(!index.empty()) {
lastPos = index.back();
}
maxSize = max(maxSize, i - lastPos);
} else {
index.push_back(i);
}
}
}
return maxSize;
}
int main(void) {
cout << longestValidParentheses("())()") << endl;
}
~