> For the complete documentation index, see [llms.txt](https://longxingtan.gitbook.io/mle-interview/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://longxingtan.gitbook.io/mle-interview/01_leetcode/09_dynamic_program/32.-longest-valid-parentheses.md).

# 32. Longest Valid Parentheses

<https://leetcode.com/problems/longest-valid-parentheses/>

## solution

* 动态规划
  * 以s\[i]结尾的字符串能够构成的最长的匹配串的长度

```python
# https://zhuanlan.zhihu.com/p/110240060


```

时间复杂度：O()\
空间复杂度：O()

* 经典做法
  * 一个栈维护左括号的下标，然后遇到匹配的右括号时弹出左括号并通过下标计算长度

```python
class Solution:
    def longestValidParentheses(self, s: str) -> int:
        max_len = 0
        stack = [-1]
        for i in range(len(s)):

            if s[i] == '(':
                stack.append(i)
            else:
                stack.pop()
                if not stack:
                    stack.append(i)
                else:
                    max_len = max(max_len, i - stack[-1])
        return max_len
```

## follow op

[括号类小结](/mle-interview/01_leetcode/07_dfs/22.-generate-parentheses.md)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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://longxingtan.gitbook.io/mle-interview/01_leetcode/09_dynamic_program/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.
