forked from mengli/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LongestValidParentheses.java
43 lines (41 loc) · 1.05 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
41
42
43
import java.util.Stack;
/**
* Given a string containing just the characters '(' and ')', find the length of
* the longest valid (well-formed) parentheses substring.
*
* For "(()", the longest valid parentheses substring is "()", which has length = 2.
*
* Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.
*/
public class LongestValidParentheses {
public int longestValidParentheses(String s) {
int length = s.length();
if (length == 0)
return 0;
int left = 0;
Stack<Integer> indexs = new Stack<Integer>();
boolean[] record = new boolean[length];
for (int i = 0; i < length; i++) {
if (s.charAt(i) == '(') {
left++;
indexs.push(i);
} else if (left > 0) {
int idx = indexs.pop();
record[idx] = true;
record[i] = true;
left--;
}
}
int ret = 0;
int current = 0;
for (int k = 0; k < length; k++) {
if (record[k]) {
current++;
} else {
ret = current > ret ? current : ret;
current = 0;
}
}
return ret > current ? ret : current;
}
}