-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0032-longest-valid-parentheses.cpp
More file actions
40 lines (36 loc) · 1017 Bytes
/
0032-longest-valid-parentheses.cpp
File metadata and controls
40 lines (36 loc) · 1017 Bytes
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
class Solution {
public:
int longestValidParentheses(string s) {
if (s.empty()) return 0;
int stk[s.size()];
int f[s.size()];
int top = 0, ans = 0;
for (int j = 0; j < s.size(); j++) {
char ch = s[j];
if (ch == ')') {
if (top > 0) {
f[j] = stk[top - 1];
top--;
} else {
top = 0;
f[j] = -1;
}
} else {
stk[top] = j;
top++;
f[j] = -1;
}
}
for (int i = s.size() - 1; i >= 0; --i) {
if (f[i] != -1) {
int p = i, cur = 0;
while (p > 0 && f[p] >= 0 && s[p] == ')') {
cur += (p - f[p] + 1);
p = f[p] - 1;
}
ans = max(ans, cur);
}
}
return ans;
}
};