-
Notifications
You must be signed in to change notification settings - Fork 120
/
Copy path0402-RemoveKDigits.cs
50 lines (43 loc) · 1.42 KB
/
0402-RemoveKDigits.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
//-----------------------------------------------------------------------------
// Runtime: 84ms
// Memory Usage: 23.8 MB
// Link: https://leetcode.com/submissions/detail/338962104/
//-----------------------------------------------------------------------------
using System.Collections.Generic;
using System.Text;
namespace LeetCode
{
public class _0402_RemoveKDigits
{
public string RemoveKdigits(string num, int k)
{
if (k == 0) return num;
if (k == num.Length) return "0";
var stack = new Stack<char>();
foreach (var ch in num)
{
while (k > 0 && stack.Count > 0 && ch < stack.Peek())
{
k--;
stack.Pop();
}
stack.Push(ch);
}
while (k-- > 0 && stack.Count > 0)
stack.Pop();
if (stack.Count == 0) return "0";
var sb = new StringBuilder();
foreach (var ch in stack)
sb.Append(ch);
var result = new StringBuilder();
bool leadingZero = true;
for (int i = sb.Length - 1; i >= 0; i--)
{
if (leadingZero && sb[i] == '0') { continue; }
leadingZero = false;
result.Append(sb[i]);
}
return result.Length > 0 ? result.ToString() : "0";
}
}
}