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

How can I run a C++ program directly from Windows?

How-can-I-run-a-C-program-directly-from-Windows