-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
107 lines (90 loc) · 2.48 KB
/
main.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
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
class Solution {
public:
int longestValidParentheses(string s) {
if (s.empty()) return 0;
int n = s.size();
int result = 0;
vector<int> dp(n, 0);
for (int r = 1; r < n; ++r) {
if (s[r] == '(') continue;
int l = r - 1;
while (l >= 0 && dp[l] > 0) {
l -= dp[l];
}
if (l >= 0 && s[l] == '(') {
dp[r] = r - l + 1;
if (l > 0) dp[r] += dp[l - 1];
}
}
return *max_element(dp.begin(), dp.end());
}
};
class Solution {
public:
int longestValidParentheses(string s) {
int result = 0;
int opens = 0;
for (int l = 0, r = 0; r < s.size(); ++r) {
opens += s[r] == '(' ? 1 : -1;
if (opens < 0) {
l = r + 1;
opens = 0;
} else if (opens == 0) {
result = max(result, r - l + 1);
}
}
reverse(s.begin(), s.end());
int closes = 0;
for (int l = 0, r = 0; r < s.size(); ++r) {
closes += s[r] == ')' ? 1 : -1;
if (closes < 0) {
l = r + 1;
closes = 0;
} else if (closes == 0) {
result = max(result, r - l + 1);
}
}
return result;
}
};
class Solution {
public:
int longestValidParentheses(string s) {
int n = s.size();
int result = 0;
function<void(char)> search = [&](char open) {
for (int l = 0, r = 0, c = 0; r < n; ++r) {
c += s[r] == open ? 1 : -1;
if (c < 0) {
c = 0;
l = r + 1;
} else if (c == 0) {
result = max(result, r - l + 1);
}
}
};
search('(');
reverse(s.begin(), s.end());
search(')');
return result;
}
};
class Solution {
public:
int search(string s, char target) {
int result = 0;
for (int l = 0, r = 0, open = 0; r < s.size(); ++r) {
(s[r] == target) ? ++open : --open;
if (open < 0) {
open = 0;
l = r + 1;
} else if (open == 0) {
result = max(result, r - l + 1);
}
}
return result;
}
int longestValidParentheses(string s) {
return max(search(s, '('), search({s.rbegin(), s.rend()}, ')'));
}
};