reverse-substrings-between-each-pair-of-parentheses.cpp (849B)
1 class Solution { 2 public: 3 void reverseSubstring(string& s, int idxl, int idxr) { 4 for(int i = 0; i <= (idxr - idxl) / 2; ++i) { 5 auto temp = s[i + idxl]; 6 s[i + idxl] = s[idxr - i]; 7 s[idxr - i] = temp; 8 } 9 } 10 11 string reverseParentheses(string s) { 12 vector<int> stack {}; 13 int idx = 0; 14 15 for(char& ch : s) { 16 if(ch == '(') { 17 stack.push_back(idx); 18 } else if (ch == ')') { 19 auto idxFinal = stack[stack.size() - 1]; 20 stack.pop_back(); 21 reverseSubstring(s,idxFinal,idx); 22 } 23 idx += 1; 24 } 25 26 string res = ""; 27 for(char& ch : s) { 28 if(ch != '(' && ch != ')') { 29 res += ch; 30 } 31 } 32 return res; 33 } 34 };