![]() |
VOOZH | about |
Given a string s containing brackets and characters, the task is to find the bracket numbers for each bracket in the string. A bracket number represents the order in which a specific bracket appears as either an opening or a closing bracket.
Examples:
Input: "(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.
The approach uses a stack to track the opening brackets.
'(', we increment a counter bal, push it onto the stack, and append it to the result list. ')', we pop the top value from the stack and append it to the result list. The above two steps ensure that each bracket is assigned the correct number based on its position in the string.
1 2 2 1 3 3
Time Complexity : O(n)
Auxiliary Space : O(n)