Wednesday, May 13, 2020

Print Bracket Number using stack

Given an expression exp of length n consisting of some brackets. The task is to print the bracket numbers when the expression is being parsed.

Input:
The first line contains an integer T, the number of test cases. For each test case, there is a string exp containing the expression.

Output:
For each test case, the output is the bracket numbers of the expression.
Example:
Input:

3​
(a+(b*c))+(d/e)​
((())(()))
((((()
Output:
1 2 2 1 3 3
1 2 3 3 2 4 5 5 4 1
1 2 3 4 5 5


#code
t= int(input())
while(t>0):
    #n=int(input())
    a= str(input())
    from queue import LifoQueue
    stack = LifoQueue(maxsize = len(a))
    j = 0
    k = 0
    l = ""
    for i in range(len(a)):
        if a[i] == '(':
            j = j + 1
            stack.put(j)
            l = l + str(j)+ " "
        if a[i] == ')':
            k = stack.get()
            l = l + str(k) + " "
    print(l)
    t -= 1

No comments:

Post a Comment

Sacred Thought

5 May 2024 Hari Om Verse 50-51, chapter two:  In this chapter two Shree krishna explains a simple way of living. Free from desires and void ...