-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode0032.java
More file actions
33 lines (30 loc) · 933 Bytes
/
Copy pathLeetCode0032.java
File metadata and controls
33 lines (30 loc) · 933 Bytes
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
/* Longest Valid Parentheses
* Input: s = ")()())"
* Output: 4
* Explanation: The longest valid parentheses substring is "()()".
* */
import java.util.Stack;
public class LeetCode0032 {
public static void main(String args[]) {
String s = "()";
System.out.println(longestValidParentheses(s));
}
public static int longestValidParentheses(String s) {
int res = 0;
Stack<Integer> stack = new Stack<>();
stack.push(-1);
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(')
stack.push(i);
else {
if (stack.peek() == -1 || s.charAt(stack.peek()) == ')')
stack.push(i);
else {
stack.pop();
res = Math.max(res, i - stack.peek());
}
}
}
return res;
}
}