Reverse Substrings Between Each Pair of Parentheses

Ujjwal SharmaUjjwal Sharma
1 min read

Click Here

Approach

  1. First we will store the characters other than parenthesis because we don't want parenthesis in our answer.

  2. As soon as we encounter an opening bracket we will store it's index In the vector

  3. As all the parenthesis are guaranteed to be balanced we will keep on iterating until we find a closing bracket

  4. As soon as we encounter the closing parenthesis, we will reverse until the index of the last opening parenthesis and keep doing it until we are done with our iteration.

Code

class Solution {
public:
    string reverseParentheses(string s) {
        string ans = "" ; // initially the ans is empty string
        vector<int> index; // to store the index of the parenthesis

        for(int i = 0;i<s.length();i++){
            if(s[i]=='('){
                index.push_back(ans.size());
            }
            else if(s[i]==')'){
                int start = index.back();
                index.pop_back();
                reverse(ans.begin()+start, ans.end());
            }else{
                ans = ans+s[i];
            }
        }
        return ans;

    }
};

All the best for your DSA journey! Let me know your feedback so that we can improve this article together.

Ujjwal Sharma

0
Subscribe to my newsletter

Read articles from Ujjwal Sharma directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Ujjwal Sharma
Ujjwal Sharma