solution.md 1.5 KB
Newer Older
每日一练社区's avatar
每日一练社区 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
# 最长有效括号

<p>给你一个只包含 <code>'('</code> 和 <code>')'</code> 的字符串,找出最长有效(格式正确且连续)括号子串的长度。</p><p> </p><div class="original__bRMd"><div><p><strong>示例 1:</strong></p><pre><strong>输入:</strong>s = "(()"<strong><br />输出:</strong>2<strong><br />解释:</strong>最长有效括号子串是 "()"</pre><p><strong>示例 2:</strong></p><pre><strong>输入:</strong>s = ")()())"<strong><br />输出:</strong>4<strong><br />解释:</strong>最长有效括号子串是 "()()"</pre><p><strong>示例 3:</strong></p><pre><strong>输入:</strong>s = ""<strong><br />输出:</strong>0</pre><p> </p><p><strong>提示:</strong></p><ul>	<li><code>0 <= s.length <= 3 * 10<sup>4</sup></code></li>	<li><code>s[i]</code><code>'('</code><code>')'</code></li></ul></div></div>

## template

```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
	int longestValidParentheses(string s)
	{
		stack<int> stk;
		int invalid = -1;
		int len = 0, max_len = 0;
		for (int i = 0; i < s.length(); i++)
		{
			if (s[i] == '(')
			{
				stk.push(i);
			}
			else
			{
				if (stk.empty())
				{
					invalid = i;
				}
				else
				{
					stk.pop();
					if (stk.empty())
					{
						max_len = max(i - invalid, max_len);
					}
					else
					{
						max_len = max(i - stk.top(), max_len);
					}
				}
			}
		}
		return max_len;
	}
};
```

## 答案

```cpp

```

## 选项

### A

```cpp

```

### B

```cpp

```

### C

```cpp

```