| | 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 | | namespace LeetCode.Algorithms.RemoveAllOccurrencesOfSubstring; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class RemoveAllOccurrencesOfSubstringStack : IRemoveAllOccurrencesOfSubstring |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n) |
| | 19 | | /// Space complexity - O(n) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="s"></param> |
| | 22 | | /// <param name="part"></param> |
| | 23 | | /// <returns></returns> |
| | 24 | | public string RemoveOccurrences(string s, string part) |
| 3 | 25 | | { |
| 3 | 26 | | var stack = new Stack<char>(); |
| | 27 | |
|
| 129 | 28 | | foreach (var c in s) |
| 60 | 29 | | { |
| 60 | 30 | | stack.Push(c); |
| | 31 | |
|
| 60 | 32 | | if (stack.Count < part.Length) |
| 32 | 33 | | { |
| 32 | 34 | | continue; |
| | 35 | | } |
| | 36 | |
|
| 28 | 37 | | var tempStack = new Stack<char>(); |
| | 38 | |
|
| 144 | 39 | | for (var i = part.Length - 1; i >= 0; i--) |
| 63 | 40 | | { |
| 63 | 41 | | if (stack.Peek() == part[i]) |
| 44 | 42 | | { |
| 44 | 43 | | tempStack.Push(stack.Pop()); |
| 44 | 44 | | } |
| | 45 | | else |
| 19 | 46 | | { |
| 20 | 47 | | while (tempStack.Count > 0) |
| 1 | 48 | | { |
| 1 | 49 | | stack.Push(tempStack.Pop()); |
| 1 | 50 | | } |
| | 51 | |
|
| 19 | 52 | | break; |
| | 53 | | } |
| 44 | 54 | | } |
| 28 | 55 | | } |
| | 56 | |
|
| 3 | 57 | | var result = new char[stack.Count]; |
| | 58 | |
|
| 40 | 59 | | for (var i = result.Length - 1; i >= 0; i--) |
| 17 | 60 | | { |
| 17 | 61 | | result[i] = stack.Pop(); |
| 17 | 62 | | } |
| | 63 | |
|
| 3 | 64 | | return new string(result); |
| 3 | 65 | | } |
| | 66 | | } |