Reverse Substrings Between Each Pair of Parentheses Solutions in C++
Number 1190
Difficulty Medium
Acceptance 61.5%
Link LeetCode
Other languages —
Solutions
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses//// Author : liuyubobobo/// Time : 2019-09-14#include <iostream>#include <stack>using namespace std;/// Using Stack/// Time Complexity: O(n^2)/// Space Complexity: O(n)class Solution {public:string reverseParentheses(string s) {string p = "", res = "";stack<int> stack;for(int i = 0; i < s.size(); i ++)if(s[i] == ')'){// cout << stack.top() << endl;string t = p.substr(stack.top() + 1);reverse(t.begin(), t.end());p = p.substr(0, p.size() - (t.size() + 1));p += t;stack.pop();}else{p += s[i];if(s[i] == '(') stack.push(p.size() - 1);}return p;}};int main() {cout << Solution().reverseParentheses("(abcd)") << endl;// dcbacout << Solution().reverseParentheses("(u(love)i)") << endl;// iloveucout << Solution().reverseParentheses("(ed(et(oc))el)") << endl;// leetcodecout << Solution().reverseParentheses("a(bcdefghijkl(mno)p)q") << endl;// apmnolkjihgfedcbqreturn 0;}
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses//// Author : liuyubobobo/// Time : 2019-09-15#include <iostream>#include <stack>using namespace std;/// Recursion/// Time Complexity: O(n^2)/// Space Complexity: O(n)class Solution {public:string reverseParentheses(string s) {int start;for(int i = 0; i < s.size(); i ++)if(s[i] == '(') start = i;else if(s[i] == ')'){string t = s.substr(start + 1, i - (start + 1));reverse(t.begin(), t.end());return reverseParentheses(s.substr(0, start) + t + s.substr(i + 1));}return s;}};int main() {cout << Solution().reverseParentheses("(abcd)") << endl;// dcbacout << Solution().reverseParentheses("(u(love)i)") << endl;// iloveucout << Solution().reverseParentheses("(ed(et(oc))el)") << endl;// leetcodecout << Solution().reverseParentheses("a(bcdefghijkl(mno)p)q") << endl;// apmnolkjihgfedcbqreturn 0;}