-
Notifications
You must be signed in to change notification settings - Fork 2
/
LongestValidParentheses.java
40 lines (33 loc) · 1.1 KB
/
LongestValidParentheses.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
35
36
37
38
39
40
package leetcode.string;
import java.util.Stack;
public class LongestValidParentheses {
private static final char OPEN = 40;
public int longestValidParentheses(String s) {
Stack<Integer> ranges = new Stack<>();
// Makes sure the stack is only left with those who are not in the valid ranges.
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == OPEN) {
ranges.push(i);
} else if (!ranges.isEmpty() && s.charAt(ranges.peek()) == OPEN) {
ranges.pop();
} else {
ranges.push(i);
}
}
// Returns if the whole string is valid.
if (ranges.isEmpty()) {
return s.length();
}
// Finds the largest consecutive range.
int right = s.length() - 1;
int soFar = 0;
while(right >= 0 && !ranges.isEmpty()) {
int left = ranges.pop();
if (right - left > soFar) {
soFar = right - left;
}
right = left - 1;
}
return Math.max(soFar, right + 1);
}
}