-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path402RemoveKDigits.java
More file actions
38 lines (28 loc) · 926 Bytes
/
402RemoveKDigits.java
File metadata and controls
38 lines (28 loc) · 926 Bytes
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
//https://leetcode.com/problems/remove-k-digits/
class Solution {
public String removeKdigits(String num, int k) {
ArrayDeque<Character> queue = new ArrayDeque<>();
for(char ch : num.toCharArray())
{
while(!queue.isEmpty() && queue.peekFirst() > ch && k > 0)
{
queue.removeFirst();
k--;
}
queue.addFirst(ch);
}
while(!queue.isEmpty() && k > 0)
{
queue.removeFirst();
k--;
}
StringBuilder sb = new StringBuilder();
while(!queue.isEmpty() && queue.peekLast() == '0'){
queue.removeLast();
}
while(!queue.isEmpty()){
sb.append(queue.removeLast());
}
return sb.length() == 0? "0" : sb.toString();
}
}