> For the complete documentation index, see [llms.txt](https://txfs19260817.gitbook.io/leetcode-go-notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://txfs19260817.gitbook.io/leetcode-go-notes/solutions/32.-longest-valid-parentheses.md).

# 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/)
