| | 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.RemoveKDigits; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class RemoveKDigitsStack : IRemoveKDigits |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n) |
| | 19 | | /// Space complexity - O(n) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="num"></param> |
| | 22 | | /// <param name="k"></param> |
| | 23 | | /// <returns></returns> |
| | 24 | | public string RemoveKdigits(string num, int k) |
| 8 | 25 | | { |
| 8 | 26 | | if (k == num.Length) |
| 2 | 27 | | { |
| 2 | 28 | | return "0"; |
| | 29 | | } |
| | 30 | |
|
| 6 | 31 | | var stack = new Stack<char>(); |
| | 32 | |
|
| 160 | 33 | | foreach (var digit in num) |
| 71 | 34 | | { |
| 92 | 35 | | while (k > 0 && stack.Count > 0 && stack.Peek() > digit) |
| 21 | 36 | | { |
| 21 | 37 | | stack.Pop(); |
| | 38 | |
|
| 21 | 39 | | k--; |
| 21 | 40 | | } |
| | 41 | |
|
| 71 | 42 | | stack.Push(digit); |
| 71 | 43 | | } |
| | 44 | |
|
| 7 | 45 | | while (k > 0 && stack.Count > 0) |
| 1 | 46 | | { |
| 1 | 47 | | stack.Pop(); |
| | 48 | |
|
| 1 | 49 | | k--; |
| 1 | 50 | | } |
| | 51 | |
|
| 6 | 52 | | var resultArray = stack.ToArray(); |
| | 53 | |
|
| 6 | 54 | | Array.Reverse(resultArray); |
| | 55 | |
|
| 6 | 56 | | var startIndex = 0; |
| | 57 | |
|
| 11 | 58 | | while (startIndex < resultArray.Length && resultArray[startIndex] == '0') |
| 5 | 59 | | { |
| 5 | 60 | | startIndex++; |
| 5 | 61 | | } |
| | 62 | |
|
| 6 | 63 | | return startIndex == resultArray.Length |
| 6 | 64 | | ? "0" |
| 6 | 65 | | : new string(resultArray, startIndex, resultArray.Length - startIndex); |
| 8 | 66 | | } |
| | 67 | | } |