-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0032.最长有效括号.cpp
73 lines (70 loc) · 1.64 KB
/
0032.最长有效括号.cpp
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
/*
* @lc app=leetcode.cn id=32 lang=cpp
*
* [32] 最长有效括号
*
* https://leetcode-cn.com/problems/longest-valid-parentheses/description/
*
* algorithms
* Hard (28.04%)
* Likes: 386
* Dislikes: 0
* Total Accepted: 27.8K
* Total Submissions: 96.8K
* Testcase Example: '"(()"'
*
* 给定一个只包含 '(' 和 ')' 的字符串,找出最长的包含有效括号的子串的长度。
*
* 示例 1:
*
* 输入: "(()"
* 输出: 2
* 解释: 最长有效括号子串为 "()"
*
*
* 示例 2:
*
* 输入: ")()())"
* 输出: 4
* 解释: 最长有效括号子串为 "()()"
*
*
*/
// @lc code=start
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
int longestValidParentheses(string s)
{
vector<int> dp(s.size(), 0);
int i = 1;
int max_len = 0;
while (i < s.size()) {
if (s[i] == ')') {
if (s[i - 1] == '(') {
if (i >= 2) {
dp[i] = dp[i - 2] + 2;
} else {
dp[i] = 2;
}
} else {
if (i - dp[i - 1] - 1 >= 0 && s[i - dp[i - 1] - 1] == '(') {
if (i - dp[i - 1] - 2 > 0) {
dp[i] = dp[i - 1] + dp[i - dp[i - 1] - 2] + 2;
} else {
dp[i] = dp[i - 1] + 2;
}
}
}
}
if (dp[i] > max_len) {
max_len = dp[i];
}
++i;
}
return max_len;
}
};
// @lc code=end