Skip to content

Commit 03f3aab

Browse files
authored
Create Solution2.java
1 parent aa4b61f commit 03f3aab

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Solution {
2+
public int longestValidParentheses(String s) {
3+
int res = 0;
4+
for (int i = 0, left = 0, right = 0; i < s.length(); ++i) {
5+
if (s.charAt(i) == '(') {
6+
++left;
7+
} else {
8+
++right;
9+
}
10+
if (left == right) {
11+
res = Math.max(res, left << 1);
12+
} else if (left < right) {
13+
left = 0;
14+
right = 0;
15+
}
16+
}
17+
for (int i = s.length() - 1, left = 0, right = 0; i >= 0; --i) {
18+
if (s.charAt(i) == '(') {
19+
++left;
20+
} else {
21+
++right;
22+
}
23+
if (left == right) {
24+
res = Math.max(res, left << 1);
25+
} else if (left > right) {
26+
left = 0;
27+
right = 0;
28+
}
29+
}
30+
return res;
31+
}
32+
}

0 commit comments

Comments
 (0)