<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:
    # (num of open, num of closed successfully)
    def longestValidParentheses(self, s: str) -> int:
        stack = []
        for c in s:
            if c == '(':
                num_open = 0
                if stack and stack[-1][1] == 0:
                    num_open = stack.pop()[0]
                stack.append((num_open + 1, 0))
            elif stack:
                if stack[-1][0] <= 0:
                    stack.append((-1,-1))
                else:
                    tmp = stack.pop()
                    stack.append((tmp[0] - 1, tmp[1] + 1))
                    num_close = 0
                    while stack and stack[-1][0] == 0:
                        num_close += stack.pop()[1]
                    tmp = stack.pop() if stack and stack[-1][0]!=-1 else (0, 0)
                    stack.append((tmp[0], tmp[1]+num_close))
        return (max(stack, key=lambda pair: pair[1])[1])*2 if stack else 0
16800