<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: str) -> int:
        if not s:
            return 0
        valid = [False] * len(s)
        stack = deque()
        for r in range(len(s)):
            assert s[r] in ["(", ")"]
            if s[r] == "(":
                stack.append(r)
            elif stack:
                l = stack.pop()
                valid[l] = True
                valid[r] = True
        max_length = 0
        l = -1
        for r in range(len(valid)):
            if valid[r]:
                if l == -1:
                    l = r
            elif l >= 0:
                length = r - l
                max_length = max(max_length, length)
                l = -1
        if valid[len(valid) - 1]:
            length = len(valid) - l
            max_length = max(max_length, length)
        return max_length
17600