<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:
    def longestValidParentheses(self, s):
        if len(s) < 2:
            return 0
        
        # contains [opens, len]
        heads = []
        max = 0
        
        for c in s:
            if c == '(':
                for e in heads:
                    e[0] = e[0] + 1
                heads.append([1,0])
            else:
                for i in range(len(heads)-1, -1, -1):
                    e = heads[i]
                    e[0] = e[0] - 1
                    e[1] = e[1] + 2
                    if e[0] == 0:
                        if e[1] > max:
                            max = e[1]
                    if e[0] == -1:
                        # invalid
                        del heads[i]

        return max


18200