-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathValid_Substring.java
64 lines (58 loc) · 1.45 KB
/
Valid_Substring.java
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// { Driver Code Starts
//Initial Template for Java
import java.io.*;
import java.util.*;
class GFG {
public static void main(String args[]) throws IOException {
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(read.readLine());
while (t-- > 0) {
String S = read.readLine();
Solution ob = new Solution();
System.out.println(ob.findMaxLen(S));
}
}
}
// User function Template for Java
class Solution {
static int findMaxLen(String S) {
int n = S.length();
if (S == null || n == 0) {
return 0;
}
Stack<Integer> st = new Stack<>();
st.push(-1);
int maxLen = 0;
for (int i = 0; i < n; i++) {
char curr = S.charAt(i);
if (curr == '(') {
st.push(i);
} else {
st.pop();
if (st.isEmpty()) {
st.push(i);
}
maxLen = Math.max(maxLen, i - st.peek());
}
}
return maxLen;
// int n = S.length();
// HashMap<Integer, Integer> map = new HashMap<>();
// int maxLen = 0;
// int sum = 0;
// for(int i = 0; i<n; i++){
// sum += S.charAt(i) == '(' ? 1 : -1;
// if( sum == 0 && maxLen == 0 ){
// maxLen = 1;
// }
// if( sum == 0 ) maxLen = i+1;
// if( map.containsKey(sum) ){
// int prevIndex = map.get(sum);
// maxLen = Math.max(maxLen, i - prevIndex );
// }else{
// map.put(sum, i);
// }
// }
// return maxLen;
}
};