-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestValidParentheses.cpp
More file actions
50 lines (48 loc) · 926 Bytes
/
Copy pathLongestValidParentheses.cpp
File metadata and controls
50 lines (48 loc) · 926 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
41
42
43
44
45
46
47
48
49
class Solution {
public:
int longestValidParentheses(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int n = s.size();
int i = 0;
int max = 0;
int left = 0;
int start = 0;
while (i < n) {
if (s[i] == '(') {
left++;
} else if (left) {
left--;
if (left == 0) {
if (i - start + 1 > max)
max = i - start + 1;
}
} else {
start = i + 1;
}
i++;
}
if (!left)
return max;
i = n - 1;
int end = start;
start = i;
int right = 0;
while (i >= end) {
if (s[i] == ')')
right++;
else if (right) {
right--;
if (right == 0) {
if (start - i + 1 > max) {
max = start - i + 1;
}
}
} else {
start = i - 1;
}
i--;
}
return max;
}
};