Reverse Substrings Between Each Pair of Parentheses in C++


Suppose we have a string s that consists of lower case letters and brackets. We have to reverse the strings in each pair of matching parentheses, starting from the innermost one. And the result should not contain any brackets. So if the input is like "(hel(lowo)rld)", then the output will be "dlrlowoleh", so from the beginning, it is changed like: "(hel(lowo)rld)" → "(helowolrld)" → “dlrowoleh”.

To solve this, we will follow these steps −

  • n := size of string, make an array called par whose length is n, define a stack st

  • for i in range 0 to n – 1

    • if s[i] is opening parentheses, then insert i into st

    • otherwise when s[i] is closing parentheses, then j := st.pop(), par[i] := j and par[j] := i

  • Define one empty string ret

  • for i := 0, d := 1, i < n, increase i by d

    • if s[i] is opening parentheses or s[i] is closing parentheses, then i := par[i], d := -d otherwise increase ret by s[i]

  • return ret

Example (C++)

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   void out(vector <int>& v){
      for(int i = 0; i < v.size(); i++){
         cout << v[i] << " " ;
      }
      cout << endl;
   }
   string reverseParentheses(string s) {
      int n = s.size();
      vector <int> par(n);
      stack <int> st;
      for(int i = 0; i < n; i++){
         if(s[i] == '('){
            st.push(i);
         }
         else if(s[i] == ')'){
            int j = st.top();
            st.pop();
            par[i] = j;
            par[j] = i;
         }
      }
      string ret = "";
      for(int i = 0, d = 1; i < n; i += d){
         if(s[i] == '(' || s[i] == ')'){
            i = par[i];
            d = -d;
         }
         else{
            ret += s[i];
         }
      }
      out(par);
      return ret;
   }
};
main(){
   Solution ob;
   cout << (ob.reverseParentheses("(hel(lowo)rld)"));
}

Input

"(hel(lowo)rld)"

Output

13 0 0 0 9 0 0 0 0 4 0 0 0 0
dlrlowoleh

Updated on: 29-Apr-2020

239 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements