Sponsored
Sponsored
Utilize a stack to handle the nested or paired parentheses efficiently. By pushing characters onto a stack until a closing parenthesis is encountered, then reversing the needed substring, you can leverage the stack's LIFO properties to achieve the desired result.
Time Complexity: O(n).
Space Complexity: O(n) due to the stack usage for storing characters.
1function reverseParentheses(s) {
2 let stack = [];
3 for (let char of s) {
4 if (char === ')') {
5 let queue = [];
6 while (stack.length && stack[stack.length - 1] !== '(') {
7 queue.push(stack.pop());
8 }
9 stack.pop(); // pop '('
10 stack.push(...queue);
11 } else {
12 stack.push(char);
13 }
14 }
15 return stack.join('');
16}
17
18console.log(reverseParentheses('(u(love)i)'));
19
The JavaScript solution uses an array functioning as a stack to manage the sequence assembly and reversal process. It offers efficient character stacking and substring reversal through JavaScript's flexible array structure, enhancing the code's readability and maintainability.
This approach involves separately building the result string in a single pass using an auxiliary data structure to track position swaps. The use of local in-string reversals enables an efficient and clean traversal building mechanism.
Time Complexity: O(n).
Space Complexity: O(n), using additional space for parentheses pair tracking and intermediate char arrays.
#include <vector>
#include <stack>
using namespace std;
string reverseParentheses(string s) {
int n = s.length();
vector<int> pair(n, 0);
stack<int> st;
for (int i = 0; i < n; i++) {
if (s[i] == '(') st.push(i);
else if (s[i] == ')') {
int j = st.top(); st.pop();
pair[i] = j;
pair[j] = i;
}
}
string result;
for (int i = 0, d = 1; i < n; i += d) {
if (s[i] == '(' || s[i] == ')') {
i = pair[i];
d = -d;
} else {
result += s[i];
}
}
return result;
}
int main() {
string s = "(ed(et(oc))el)";
cout << reverseParentheses(s) << endl;
return 0;
}
This C++ solution uses a vector for holding paired indices and a stack to manage parenthesis processing. The method effectively accounts for necessary positional reversals, facilitating a clean string pass strategy to build results without additional data structure overhead.