# LeetCode 32. Longest Valid Parentheses

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 * 10^4`
* `s[i]` is `'('`, or `')'`.

[English Version in Youtube](https://youtu.be/APvAgoFcFYQ)

[中文版解答Youtube Link](https://youtu.be/7sLZoD05uxw)

[中文版解答Bilibili Link](https://www.bilibili.com/video/BV13z4y117uv/)

## Solution 1: Dynamic Programming

```
class Solution {
public:
    int longestValidParentheses(string s) {
        int n = s.size();
        int res = 0;
        vector<int> dp(n, 0);
        for (int i = 0; i < n; i++) {
            if (i > 0 && s[i] == ')') {
                if (s[i-1] == '(') {
                    int val = i - 2 >= 0 ? dp[i-2] : 0;
                    dp[i] = 2 + val;
                } else {
                    int ind = i - dp[i-1] - 1;
                    if (ind >= 0 && s[ind] == '(') {
                        int val = ind > 0 ? dp[ind - 1] : 0;
                        dp[i] = 2 + dp[i-1] + val;
                    }
                }
                res = max(res, dp[i]);
            }
        }
        return res;
    }
};
```

## Solution 2: Stack

```
class Solution {
public:
    int longestValidParentheses(string s) {
        stack<int> mystack;
        mystack.push(-1);
        int res = 0;
        for (int i = 0; i < s.size(); i++) {
            int t = mystack.top();
            if (t != -1 && s[i] == ')' && s[t]=='(') {
                mystack.pop();
                res = max(res, i - mystack.top());
            } else {
                mystack.push(i);
            }
        }
        return res;
    }
};
```


---

# 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://zhenchaogan.gitbook.io/leetcode-solution/leetcode-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.
