-
-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathFebruary-22.java
61 lines (53 loc) · 1.48 KB
/
February-22.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
//{ Driver Code Starts
// Initial Template for Java
import java.io.*;
import java.util.*;
class GFG {
public static void main(String args[]) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(in.readLine());
while (t-- > 0) {
String S = in.readLine();
Solution ob = new Solution();
System.out.println(ob.maxLength(S));
System.out.println("~");
}
}
}
// } Driver Code Ends
class Solution {
static int maxLength(String s) {
int l = 0, r = 0, m = 0;
for (char c : s.toCharArray()) {
if (c == '(') l++;
else r++;
if (l == r) m = Math.max(m, 2 * r);
else if (r > l) l = r = 0;
}
l = r = 0;
for (int i = s.length() - 1; i >= 0; i--) {
if (s.charAt(i) == '(') l++;
else r++;
if (l == r) m = Math.max(m, 2 * l);
else if (l > r) l = r = 0;
}
return m;
}
}
2)
class Solution {
static int maxLength(String s) {
java.util.Stack<Integer> st = new java.util.Stack<>();
st.push(-1);
int m = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') st.push(i);
else {
st.pop();
if (st.empty()) st.push(i);
else m = Math.max(m, i - st.peek());
}
}
return m;
}
}