---
description: LeetCode 32
---

# Longest Valid Parentheses

```python
class Solution:
    def longestValidParentheses(self, s):
        """
        :type s: str
        :rtype: int
        """
        stack = [0]
        res = 0       
        """
        Parentheses 題目大多可以用 stack 解決
        只是往stack裏頭丟的東西不同
        目前遇到就兩招:
        (1) 丟符號
        (2) 丟數字: 此題是用stack[-1]來記錄當前合法數
        """
        for l in s:
            if l == '(':
                stack.append(0)
            else:
                # ')'
                if len(stack) > 1:
                    val = stack.pop()
                    stack[-1] += val + 2
                    res = max(stack[-1], res)
                    print(res)
                else:
                    stack = [0]
        return res
                
```
