-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathP18.java
More file actions
37 lines (30 loc) · 862 Bytes
/
P18.java
File metadata and controls
37 lines (30 loc) · 862 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
35
36
37
package stack_and_queue;
import java.util.Stack;
// Length of the longest valid substring
public class P18 {
public static int findMaxLen(String s) {
Stack<Character> st = new Stack<>();
Stack<Integer> index = new Stack<>();
int length, max = 0;
index.push(-1);
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i) == '(') {
st.push(s.charAt(i));
index.push(i);
}
else {
if(!st.isEmpty()) {
st.pop();
index.pop();
length = i - index.peek();
if(max < length)
max = length;
}
index.push(i);
}
}
return max;
}
public static void main(String[] args) {
}
}