<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) {
        int count = 0;
        if(s=="") return(0);
        stack<int> st;
        int res = 0;
        int cur = 0;
        for(char c:s){
            if(c=='(') {
                if(cur>0) {
                    while( !st.empty()&& st.top()>1){
                        cur+=st.top();
                        st.pop();
                    }
                    st.push(cur);
                    res = max(res,cur);
                    cur = 0;
                }
                st.push(1);
                
            }
            if(c==')' && !st.empty()){
                if(st.top()==1) {
                    st.pop();
                    cur +=2;
                   
                } else {
                    while( !st.empty()&& st.top()>1){
                        cur+=st.top();
                        st.pop();
                    }
                    if(st.empty()){
                        res = max(res,cur);
                        cur = 0;
                    } else {
                        st.pop();
                        cur +=2;
                    }
                }

            } else{
                res = max(res,cur);
                cur = 0;
            }
        }
        while( !st.empty()&& st.top()>1){
                        cur+=st.top();
                        st.pop();
                    }
                    res = max(res,cur);
                    cur = 0;

        return res;
    }
};
10300