-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
34 lines (26 loc) · 871 Bytes
/
Copy pathSolution.java
File metadata and controls
34 lines (26 loc) · 871 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
34
import java.util.Stack;
public class Solution {
public static int longestValidParentheses(String s) {
Stack<Integer> stack = new Stack<>();
stack.push(-1);
int maxLength = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
stack.push(i);
} else {
stack.pop();
if (stack.isEmpty()) {
stack.push(i);
} else {
maxLength = Math.max(maxLength, i - stack.peek());
}
}
}
return maxLength;
}
public static void main(String[] args) {
System.out.println(longestValidParentheses("(()"));
System.out.println(longestValidParentheses(")()())"));
System.out.println(longestValidParentheses(""));
}
}