forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution2.java
32 lines (32 loc) · 896 Bytes
/
Solution2.java
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
class Solution {
public int longestValidParentheses(String s) {
int res = 0;
for (int i = 0, left = 0, right = 0; i < s.length(); ++i) {
if (s.charAt(i) == '(') {
++left;
} else {
++right;
}
if (left == right) {
res = Math.max(res, left << 1);
} else if (left < right) {
left = 0;
right = 0;
}
}
for (int i = s.length() - 1, left = 0, right = 0; i >= 0; --i) {
if (s.charAt(i) == '(') {
++left;
} else {
++right;
}
if (left == right) {
res = Math.max(res, left << 1);
} else if (left > right) {
left = 0;
right = 0;
}
}
return res;
}
}