402. Remove K Digits
class Solution {
public String removeKdigits(String num, int k) {
// greedy with stack
Deque<Character> stack = new LinkedList<>();
for(int i=0; i<num.length(); i++){
if(k>0 && stack.size()>0 && num.charAt(i)<stack.peek()){
stack.pop();
k--;
i--;
continue;
}
stack.push(num.charAt(i));
}
while(k>0){
stack.pop();
k--;
}
StringBuilder sb = new StringBuilder();
while(stack.size()>0){
// deque method: last is the bottom element of the stack
if(stack.getLast()=='0' && sb.length()==0){
stack.removeLast();
continue;
}else{
// deque method: removeLast()
sb.append(stack.removeLast());
}
}
return sb.length()>0? sb.toString() : "0";
}
}
Last updated
Was this helpful?