| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | using System.Text; |
| | 13 | |
|
| | 14 | | namespace LeetCode.Algorithms.ReverseSubstringsBetweenEachPairOfParentheses; |
| | 15 | |
|
| | 16 | | /// <inheritdoc /> |
| | 17 | | public class ReverseSubstringsBetweenEachPairOfParenthesesStack : IReverseSubstringsBetweenEachPairOfParentheses |
| | 18 | | { |
| | 19 | | /// <summary> |
| | 20 | | /// Time complexity - O(n) |
| | 21 | | /// Space complexity - O(n) |
| | 22 | | /// </summary> |
| | 23 | | /// <param name="s"></param> |
| | 24 | | /// <returns></returns> |
| | 25 | | public string ReverseParentheses(string s) |
| 3 | 26 | | { |
| 3 | 27 | | var leftParenthesesIndexStack = new Stack<int>(); |
| | 28 | |
|
| 3 | 29 | | var sArray = s.ToCharArray(); |
| | 30 | |
|
| 66 | 31 | | for (var i = 0; i < sArray.Length; i++) |
| 30 | 32 | | { |
| 30 | 33 | | switch (sArray[i]) |
| | 34 | | { |
| | 35 | | case '(': |
| 6 | 36 | | leftParenthesesIndexStack.Push(i); |
| 6 | 37 | | break; |
| | 38 | | case ')': |
| 6 | 39 | | { |
| 6 | 40 | | var left = leftParenthesesIndexStack.Pop() + 1; |
| 6 | 41 | | var right = i - 1; |
| | 42 | |
|
| 24 | 43 | | while (left < right) |
| 18 | 44 | | { |
| 18 | 45 | | (sArray[left], sArray[right]) = (sArray[right], sArray[left]); |
| | 46 | |
|
| 18 | 47 | | left++; |
| 18 | 48 | | right--; |
| 18 | 49 | | } |
| | 50 | |
|
| 6 | 51 | | break; |
| | 52 | | } |
| | 53 | | } |
| 30 | 54 | | } |
| | 55 | |
|
| 3 | 56 | | var stringBuilder = new StringBuilder(); |
| | 57 | |
|
| 69 | 58 | | foreach (var c in sArray) |
| 30 | 59 | | { |
| 30 | 60 | | if (c != '(' && c != ')') |
| 18 | 61 | | { |
| 18 | 62 | | stringBuilder.Append(c); |
| 18 | 63 | | } |
| 30 | 64 | | } |
| | 65 | |
|
| 3 | 66 | | return stringBuilder.ToString(); |
| 3 | 67 | | } |
| | 68 | | } |