Print Bracket Number
Given a string str, the task is to find the bracket numbers, i.e., for each bracket in str, return i if the bracket is the ith opening or closing bracket to appear in the string.
Examples:
Input: str = "(aa(bdc))p(dee)"
Output: 1 2 2 1 3 3
Explanation: The highlighted brackets in
the given string (aa(bdc))p(dee) are
assigned the numbers as: 1 2 2 1 3 3.
Input: str = "(((()("
Output: 1 2 3 4 4 5
Explanation: The highlighted brackets in
the given string (((()( are assigned
the numbers as: 1 2 3 4 4 5
Expected Time Complexity: O(|str|)
Expected Auxiliary Space: O(|str|)
import java.util.*;
public class BracketNumbersStack {
public static void main(String[] args) {
String str = "(aa(bdc))p(dee)";
List<Integer> result = getBracketNumbers(str);
for (int num : result) {
System.out.print(num + " ");
}
}
public static List<Integer> getBracketNumbers(String str) {
Stack<Integer> stack = new Stack<>();
List<Integer> output = new ArrayList<>();
int count = 0; // to assign numbers to opening brackets
for (char c : str.toCharArray()) {
if (c == '(') {
count++;
stack.push(count);
output.add(count); // opening bracket gets new number
} else if (c == ')') {
int openNum = stack.pop(); // closing bracket matches opening
output.add(openNum);
}
// ignore other chars
}
return output;
}
}
Comments
Post a Comment