-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbracketNumber.java
More file actions
46 lines (40 loc) · 1.24 KB
/
bracketNumber.java
File metadata and controls
46 lines (40 loc) · 1.24 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
40
41
42
43
44
45
46
//{ 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));
PrintWriter out = new PrintWriter(System.out);
int t = Integer.parseInt(read.readLine());
while (t-- > 0) {
String S = read.readLine();
Solution ob = new Solution();
ArrayList<Integer> result = ob.bracketNumbers(S);
for (int value : result) out.print(value + " ");
out.println();
}
out.close();
}
}
// } Driver Code Ends
// User function Template for Java
class Solution {
ArrayList<Integer> bracketNumbers(String str) {
ArrayList<Integer> result = new ArrayList<>();
Stack<Integer> stack = new Stack<>();
int count = 1;
for (char ch : str.toCharArray()) {
if (ch == '(') {
stack.push(count);
result.add(count);
count++;
} else if (ch == ')') {
if (!stack.isEmpty()) {
result.add(stack.pop());
}
}
}
return result;
}
}