<p>Given a string containing just the characters <code>&#39;(&#39;</code> and <code>&#39;)&#39;</code>, return <em>the length of the longest valid (well-formed) parentheses </em><span data-keyword="substring-nonempty"><em>substring</em></span>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;(()&quot;
<strong>Output:</strong> 2
<strong>Explanation:</strong> The longest valid parentheses substring is &quot;()&quot;.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;)()())&quot;
<strong>Output:</strong> 4
<strong>Explanation:</strong> The longest valid parentheses substring is &quot;()()&quot;.
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;&quot;
<strong>Output:</strong> 0
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>0 &lt;= s.length &lt;= 3 * 10<sup>4</sup></code></li>
	<li><code>s[i]</code> is <code>&#39;(&#39;</code>, or <code>&#39;)&#39;</code>.</li>
</ul>

class Solution {
public:
    int longestValidParentheses(string s) {
    stack<int> open;
    int n = s.size();
    int ans = 0;
    vector<pair<int, int>> segs;
    for(int i = 0; i < n; i++){
        if(s[i] == ')' && open.size() == 0){
            while(open.size() > 0) open.pop();
        } else if(s[i] == ')') {
            segs.push_back(make_pair(open.top(), i));
            open.pop();
        } else {
            open.push(i);
        }
    } 
    // debug(segs);
    sort(segs.begin(), segs.end());
    if(segs.size() == 0) return 0;
    int cur = 0;
    int st = segs[0].first, ed = segs[0].second;
    while(cur < segs.size()) {
        int segst = segs[cur].first;
        int seged = segs[cur].second;
       if(segst > st && seged < ed) {
            cur++;
            continue;
        } else if(segst == ed + 1) {
            ed = seged;
        } else {
            ans = max(ans, ed - st + 1);
            st = segst;
            ed = seged;
        }
        cur++;
    }
    // debug(st, ed);
    ans = max(ans, ed - st + 1);
    // debug(ans);
    return ans;
}
};
9900