forked from walkccc/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0032.cpp
More file actions
39 lines (35 loc) · 864 Bytes
/
0032.cpp
File metadata and controls
39 lines (35 loc) · 864 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
class Solution {
public:
int longestValidParentheses(string s) {
int ans = 0;
int left = 0;
int right = 0;
for (int i = 0; i < s.size(); i++) {
if (s[i] == '(')
left++;
else
right++;
if (left == right)
ans = max(ans, 2 * right);
else if (right > left) {
left = 0;
right = 0;
}
}
left = 0;
right = 0;
for (int i = s.size() - 1; i >= 0; i--) {
if (s[i] == '(')
left++;
else
right++;
if (left == right)
ans = max(ans, 2 * left);
else if (left > right) {
left = 0;
right = 0;
}
}
return ans;
}
};