-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathRemoveKDigits.java
More file actions
44 lines (35 loc) · 1.05 KB
/
RemoveKDigits.java
File metadata and controls
44 lines (35 loc) · 1.05 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
class Solution {
public String removeKdigits(String num, int k)
{
if(k == num.length())
return "0";
Stack<Character> stack = new Stack<>();
int i=0;
while(i < num.length())
{
char ch = num.charAt(i);
//whenever meet a digit which is less than the previous digit, discard the previous one
while(!stack.isEmpty() && stack.peek() > ch && k > 0)
{
stack.pop();
k--;
}
stack.push(ch);
i++;
}
//for corne case like 1111
while(k > 0)
{
stack.pop();
k--;
}
//constructing number from stack
StringBuilder sb = new StringBuilder();
while(!stack.isEmpty())
sb.append(stack.pop());
sb.reverse();
while(sb.charAt(0) == '0' && sb.length() > 1)
sb.deleteCharAt(0);
return sb.toString();
}
}