-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemove K Digits.java
More file actions
47 lines (40 loc) · 1.11 KB
/
Remove K Digits.java
File metadata and controls
47 lines (40 loc) · 1.11 KB
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
class Solution {
public String removeKdigits(String num, int k) {
int length = num.length();
if(num.length() == k)
return "0";
Stack<Integer> mono_stack = new Stack<>();
for(int i=0; i<num.length(); i++)
{
int number = Integer.parseInt(String.valueOf(num.charAt(i)));
while(!mono_stack.empty() && mono_stack.peek() > number && k > 0)
{
mono_stack.pop();
k--;
}
mono_stack.push(number);
}
while(k > 0)
{
mono_stack.pop();
k--;
}
String result = "";
Iterator<Integer> itr = mono_stack.iterator();
boolean isFound = true;
while(itr.hasNext())
{
int x = itr.next();
if(x == 0 && isFound)
continue;
else
{
isFound = false;
result+=x;
}
}
if(result.equals(""))
result = "0";
return result;
}
}