Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- int main()
- {
- string s;
- cin>>s;
- int n = s.length();
- // stack to store indices where the opening brackets occured
- stack<int> st;
- st.push(0); // '0' pushed for reference to handle base cases
- // to store positions where opening brackets to be pushed
- vector<int> store;
- for(int i=0;i<n;i++)
- {
- if(s[i]=='{'){
- st.push(i); // push the position of opening bracket
- }
- else if(st.size()>1){
- st.pop(); // we have a balanced bracket here
- }
- else{
- // we have reached a state where we have closing bracket but we don't have
- // any opening bracket that has occured earlier
- // push position for opening bracket
- store.push_back(st.top());
- }
- }
- int j=0;
- string ans = "";
- for(int i=0;i<n;i++)
- {
- // push oepning bracket till we have the condition being true
- while(j<store.size() and store[j]==i){
- ans+='{';
- j++;
- }
- ans+=s[i];
- }
- // consider the case where stack size is greater than 1
- // it means we have some positions of opening brackets but we don't have positions of closing brackets
- // we need to add that
- while(st.size()>1){
- ans+='}';
- st.pop();
- }
- cout<<ans;
- }
Add Comment
Please, Sign In to add comment