<p>You are given a string <code>s</code> that consists of lower case English letters and brackets.</p>

<p>Reverse the strings in each pair of matching parentheses, starting from the innermost one.</p>

<p>Your result should <strong>not</strong> contain any brackets.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;(abcd)&quot;
<strong>Output:</strong> &quot;dcba&quot;
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;(u(love)i)&quot;
<strong>Output:</strong> &quot;iloveu&quot;
<strong>Explanation:</strong> The substring &quot;love&quot; is reversed first, then the whole string is reversed.
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;(ed(et(oc))el)&quot;
<strong>Output:</strong> &quot;leetcode&quot;
<strong>Explanation:</strong> First, we reverse the substring &quot;oc&quot;, then &quot;etco&quot;, and finally, the whole string.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= s.length &lt;= 2000</code></li>
	<li><code>s</code> only contains lower case English characters and parentheses.</li>
	<li>It is guaranteed that all parentheses are balanced.</li>
</ul>

class Solution {
public:
    string reverseParentheses(string s) {
        string save;
        for (auto i : s) {
            if (i != ')') {
                save.push_back(i);
            } else {
                string tmp = "";
                while (save.back() != '(') {
                    tmp.push_back(save.back());
                    save.pop_back();
                }
                save.pop_back();  // Safely remove '('
                save.append(tmp);  // Efficiently append the reversed content
            }
        }
        return save;
    }
};

/*
Time Complexity: O(n)

	•	Reason:
	•	The function iterates over the string s exactly once, which takes O(n) time, where n is the length of the string.
	•	Operations such as push_back, pop_back, and append are all O(1) in amortized time.
	•	Hence, the overall time complexity of the function is O(n).

Space Complexity: O(n)

	•	Reason:
	•	In the worst case, the stack or save string may store up to O(n) characters (if no closing parentheses are encountered or if all characters are part of balanced parentheses).
	•	Thus, the space complexity is O(n).


Best Solution:

class Solution {
public:
    static string reverseParentheses(string& s) {
        string stack, rev;
        for(char c: s){
            if (c!=')') stack.push_back(c);
            else{
                rev="";
                char r=stack.back();
                for(; r!='('; r=stack.back()){
                    rev+=r;
                    stack.pop_back();
                }
                stack.pop_back();
                stack+=rev;
            }
        }
        return stack;
    }
};

*/
9100