-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestValidParanthesis.java
More file actions
39 lines (36 loc) · 1.36 KB
/
LongestValidParanthesis.java
File metadata and controls
39 lines (36 loc) · 1.36 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
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
static int getLongestParanthesis(String in) {
//trivial case
if(in.length() == 0 || in.length() == 1) return 0;
//save max length and lastIdx stores last index after which we got an opening bracket
int maxLen = 0, lastIdx = -1;
//store the indexes of opening brackets
Stack<Integer> saveIndex = new Stack<Integer>();
for(int i = 0; i < in.length(); i++) {
if(in.charAt(i) == '(') saveIndex.push(i);
else {
if(saveIndex.isEmpty()) lastIdx = i;
else {
saveIndex.pop();
if(saveIndex.isEmpty()) maxLen = Math.max(maxLen, i - lastIdx);
else maxLen = Math.max(maxLen, i - saveIndex.peek());
}
}
}
return maxLen;
}
public static void main(String args[] ) throws Exception {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
Scanner scan = new Scanner(System.in);
int q = scan.nextInt();
while(q --> 0) {
String paranthesis = scan.next();
System.out.println(getLongestParanthesis(paranthesis));
}
}
}