Given a string str that consists of lower case English letters and brackets. The task is to reverse the substrings in each pair of matching parentheses, starting from the innermost one. The result should not contain any brackets.
Examples:
Input: str = “(skeeg(for)skeeg)”
Output: geeksforgeeksInput: str = “((ng)ipm(ca))”
Output: camping
Approach: This problem can be solved using a stack. First, whenever a ‘(‘ is encountered then push the index of the element into the stack and whenever a ‘)’ is encountered then get the top element of the stack as the latest index and reverse the string between the current index and index from the top of the stack. Follow this for the rest of the string and finally print the updated string.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std; // Function to return the modified string string reverseParentheses(string str, int len) { stack< char > st; for ( int i = 0; i < len; i++) { // Push the index of the current // opening bracket if (str[i] == '(' ) { st.push(i); } // Reverse the substring starting // after the last encountered opening // bracket till the current character else if (str[i] == ')' ) { reverse(str.begin() + st.top() + 1, str.begin() + i); st.pop(); } } // To store the modified string string res = "" ; for ( int i = 0; i < len; i++) { if (str[i] != ')' && str[i] != '(' ) res += (str[i]); } return res; } // Driver code int main() { string str = "(skeeg(for)skeeg)" ; int len = str.length(); cout << reverseParentheses(str, len); return 0; } |
Python3
# Python3 implementation of the approach # Function to return the modified strring def reverseParentheses(strr, lenn): st = [] for i in range (lenn): # Push the index of the current # opening bracket if (strr[i] = = '(' ): st.append(i) # Reverse the substarting # after the last encountered opening # bracket till the current character elif (strr[i] = = ')' ): temp = strr[st[ - 1 ]:i + 1 ] strr = strr[:st[ - 1 ]] + temp[:: - 1 ] + \ strr[i + 1 :] del st[ - 1 ] # To store the modified strring res = "" for i in range (lenn): if (strr[i] ! = ')' and strr[i] ! = '(' ): res + = (strr[i]) return res # Driver code if __name__ = = '__main__' : strr = "(skeeg(for)skeeg)" lenn = len (strr) st = [i for i in strr] print (reverseParentheses(strr, lenn)) # This code is contributed by Mohit Kumar |
geeksforgeeks