-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path32.longest-valid-parentheses.cpp
More file actions
130 lines (128 loc) · 2.82 KB
/
32.longest-valid-parentheses.cpp
File metadata and controls
130 lines (128 loc) · 2.82 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
/*
* @lc app=leetcode id=32 lang=cpp
*
* [32] Longest Valid Parentheses
*
* https://leetcode.com/problems/longest-valid-parentheses/description/
*
* algorithms
* Hard (38.00%)
* Likes: 13241
* Dislikes: 463
* Total Accepted: 1.1M
* Total Submissions: 2.8M
* Testcase Example: '"(()"'
*
* Given a string containing just the characters '(' and ')', return 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 ')'.
*
*
*/
// @lc code=start
#include <stack>
#include <string>
#include <vector>
#define MEMORY 0
#define SPEED 1
#define METHOD SPEED
using namespace std;
class Solution {
public:
#if METHOD == MEMORY // 90% mem
int longestValidParentheses(string s) {
bits.resize(s.size(), false);
for (int i = 0; i < s.size(); ++i) {
if (s[i] == '(' && !bits[i]) {
int j = i + 1;
while (j < s.size() && bits[j]) ++j;
if (s[j] == ')') {
bits[i] = true;
bits[j] = true;
while (i >= 0 && bits[i]) --i;
--i;
if (i < -1) {
i = -1;
}
}
}
}
int len = 0;
int maxLen = 0;
for (int i = 0; i < bits.size(); ++i) {
if (bits[i]) {
++len;
}
else {
maxLen = max(maxLen, len);
len = 0;
}
}
maxLen = max(maxLen, len);
return maxLen;
}
private:
vector<bool> bits;
#else
public: // dp
int longestValidParentheses(string s) {
dp.resize(s.size(), 0);
int maxLen = 0;
for (int i = 1; i < s.size(); ++i) {
if (s[i] == ')') {
if (s[i-1] == '(') {
dp[i] = (i > 1 ? dp[i - 2] : 0) + 2;
}
else {
if (i - dp[i-1] - 1 >= 0 && s[i - dp[i-1] - 1] == '(') {
dp[i] = dp[i-1] + 2 + (i-dp[i-1]-2 >= 0?dp[i-dp[i-1]-2] : 0);
}
}
maxLen = max(maxLen, dp[i]);
}
}
return maxLen;
}
private:
vector <int> dp; // longestValidParentheses at i;
#endif
};
#if 0
#include <iostream>
void main() {
string s = "(()())";//"(()(((()";
Solution slt;
cout << slt.longestValidParentheses(s) << endl;
}
#endif
// @lc code=end