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.
1using System;
2using System.Collections.Generic;
3
4public class ReverseParentheses {
5 public string ReverseParentheses(string s) {
6 Stack<char> stack = new Stack<char>();
7 foreach (char c in s) {
8 if (c != ')') stack.Push(c);
9 else {
10 List<char> temp = new List<char>();
11 while (stack.Peek() != '(') {
12 temp.Add(stack.Pop());
13 }
14 stack.Pop(); // remove '('
15 foreach (char x in temp) stack.Push(x);
16 }
17 }
18 char[] result = stack.ToArray();
19 Array.Reverse(result);
20 return new string(result);
21 }
22
23 public static void Main(string[] args) {
24 ReverseParentheses rp = new ReverseParentheses();
25 Console.WriteLine(rp.ReverseParentheses("(u(love)i)"));
26 }
27}
28
This C# solution uses the Stack collection to effectively store and reverse sequences located within parentheses. By employing Stack's inherent order and systematic pushing and popping logic, it manipulates string segments with precision to achieve the desired output without parentheses.
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.
In this Java solution, indexing is managed through an array for quick access and paired swaps during parsing. This enables a simplified build process that recognizes bracket positions and adjusts in a single iteration over the string.