forked from mengli/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestValidParentheses.java
More file actions
Latest commit
43 lines (41 loc) · 1.05 KB
/
Copy pathLongestValidParentheses.java
File metadata and controls
43 lines (41 loc) · 1.05 KB
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
importjava.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.
*/
publicclassLongestValidParentheses {
publicintlongestValidParentheses(Strings) {
intlength = s.length();
if (length == 0)
return0;
intleft = 0;
Stack<Integer> indexs = newStack<Integer>();
boolean[] record = newboolean[length];
for (inti = 0; i < length; i++) {
if (s.charAt(i) == '(') {
left++;
indexs.push(i);
} elseif (left > 0) {
intidx = indexs.pop();
record[idx] = true;
record[i] = true;
left--;
}
}
intret = 0;
intcurrent = 0;
for (intk = 0; k < length; k++) {
if (record[k]) {
current++;
} else {
ret = current > ret ? current : ret;
current = 0;
}
}
returnret > current ? ret : current;
}
}