Reverse substrings between each pair of parenthesis | C ++ implementation of the approach ; Function to return the modified string ; Push the index of the current opening bracket ; Reverse the substring starting after the last encountered opening bracket till the current character ; To store the modified string ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string reverseParentheses ( string str , int len ) { stack < int > st ; for ( int i = 0 ; i < len ; i ++ ) { if ( str [ i ] == ' ( ' ) { st . push ( i ) ; } else if ( str [ i ] == ' ) ' ) { reverse ( str . begin ( ) + st . top ( ) + 1 , str . begin ( ) + i ) ; st . pop ( ) ; } } string res = " " ; for ( int i = 0 ; i < len ; i ++ ) { if ( str [ i ] != ' ) ' && str [ i ] != ' ( ' ) res += ( str [ i ] ) ; } return res ; } int main ( ) { string str = " ( skeeg ( for ) skeeg ) " ; int len = str . length ( ) ; cout << reverseParentheses ( str , len ) ; return 0 ; }