<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:
        
        openCount, closeCount = 0, 0
        res = 0
        for c in s:
            if c == "(":
                openCount += 1
            else:
                closeCount += 1
            if openCount == closeCount:
                res = max(res, openCount + closeCount)
            if closeCount > openCount:
                openCount, closeCount = 0, 0
        openCount, closeCount = 0, 0
        for c in s[::-1]:
            if c == "(":
                openCount += 1
            else:
                closeCount += 1
            if closeCount == openCount:
                res = max(res, openCount + closeCount)
            if closeCount < openCount:
                openCount, closeCount = 0, 0
            
        return res

16400