-
Notifications
You must be signed in to change notification settings - Fork 0
/
0032_Longest_Valid_Parentheses.java
34 lines (30 loc) · 1.07 KB
/
0032_Longest_Valid_Parentheses.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
33
34
class Solution {
public int longestValidParentheses(String s) {
int longest = 0;
int left = 0;
int right = 0;
int numUnclosed = 0;
for(; right < s.length(); right++) {
if(s.charAt(right) == ')') numUnclosed--;
else numUnclosed++;
if(numUnclosed == 0) longest = Math.max(longest, right - left + 1);
else if(numUnclosed < 0) { // un-opened paren is closed
left = right + 1;
numUnclosed = 0;
}
}
// do a similar iteration, backwards
int numUnopened = 0;
right = s.length() - 1;
for(left = right; left >= 0; left--) {
if(s.charAt(left) == '(') numUnopened--;
else numUnopened++;
if(numUnopened == 0) longest = Math.max(longest, right - left + 1);
else if(numUnopened < 0) { // un-closed paren is opened
right = left - 1;
numUnopened = 0;
}
}
return longest;
}
}