# 32. Longest Valid Parentheses

## LeetCode [**32. Longest Valid Parentheses**](https://leetcode-cn.com/problems/longest-valid-parentheses/)\*\*\*\*

### Description

Given a string containing just the characters `'('` and `')'`, find the length of the longest valid (well-formed) parentheses substring.

**Example 1:**

```
Input: s = "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()".
```

**Example 2:**

```
Input: s = ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()".
```

**Example 3:**

```
Input: s = ""
Output: 0
```

**Constraints:**

* `0 <= s.length <= 3 * 104`
* `s[i]` is `'('`, or `')'`.

### Tags

String, Dynamic Programming

### Solution

We make use of 2 counters `l` and `r` to count `'('` and `')'`. We iterate through the string twice, once from left to right, and once the other way around. Whenever left becomes equal to right, we calculate the length of the current valid string and keep track of maximum length substring found so far. In the forward traversal, if right becomes greater than left we reset left and right to 0, vice versa.

### Complexity

* Time complexity: $$O(n)$$
* Space complexity: $$O(1)$$

### Code

```go
func longestValidParentheses(s string) int {
	var ans, l, r int
	for i := 0; i < len(s); i++ {
		if s[i] == '(' {
			l++
		} else {
			r++
		}
		if l == r && l+r > ans {
			ans = l + r
		} else if r > l {
			l, r = 0, 0
		}
	}
	l, r = 0, 0
	for i := len(s) - 1; i >= 0; i-- {
		if s[i] == '(' {
			l++
		} else {
			r++
		}
		if l == r && l+r > ans {
			ans = l + r
		} else if r < l {
			l, r = 0, 0
		}
	}
	return ans
}
```

## Reference

1. [最长有效括号](https://leetcode-cn.com/problems/longest-valid-parentheses/solution/zui-chang-you-xiao-gua-hao-by-leetcode-solution/)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://txfs19260817.gitbook.io/leetcode-go-notes/solutions/32.-longest-valid-parentheses.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
