Stack - print bracket number

/*
example
2
(0+1)*0(0+1)*0(0+1)*
(1*0)*1*
o/p

1 1 2 2 3 3 
1 1 

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

*/

#include<bits/stdc++.h>
using namespace std;
int main()
 {
int t;
cin>>t;
while(t--)
{
    string s;
    stack <int> st;
    int c=0; // we maintain the count of open brackets
    cin>>s;
    for(int i=0;i<s.length();i++)
    {
        if(s[i]=='(')
        {c++;
        cout<<c<<" ";
        st.push(c);
        }
        if(s[i]==')')
        {
            cout<<st.top()<<" ";
            st.pop();
        }
    }
    cout<<endl;
}
return 0;
}

Comments

Popular posts from this blog

Linked List 10 operations from which problems are made ( complete guide for you)