tygarian

Balance the Parenthesis

May 17th, 2021
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main()
  5. {
  6. string s;
  7. cin>>s;
  8.  
  9. int n = s.length();
  10.  
  11. // stack to store indices where the opening brackets occured
  12. stack<int> st;
  13. st.push(0); // '0' pushed for reference to handle base cases
  14.  
  15. // to store positions where opening brackets to be pushed
  16. vector<int> store;
  17.  
  18. for(int i=0;i<n;i++)
  19. {
  20. if(s[i]=='{'){
  21. st.push(i); // push the position of opening bracket
  22. }
  23. else if(st.size()>1){
  24. st.pop(); // we have a balanced bracket here
  25. }
  26. else{
  27. // we have reached a state where we have closing bracket but we don't have
  28. // any opening bracket that has occured earlier
  29. // push position for opening bracket
  30. store.push_back(st.top());
  31. }
  32. }
  33. int j=0;
  34. string ans = "";
  35.  
  36. for(int i=0;i<n;i++)
  37. {
  38. // push oepning bracket till we have the condition being true
  39. while(j<store.size() and store[j]==i){
  40. ans+='{';
  41. j++;
  42. }
  43. ans+=s[i];
  44. }
  45.  
  46. // consider the case where stack size is greater than 1
  47. // it means we have some positions of opening brackets but we don't have positions of closing brackets
  48. // we need to add that
  49. while(st.size()>1){
  50. ans+='}';
  51. st.pop();
  52. }
  53. cout<<ans;
  54. }
Add Comment
Please, Sign In to add comment