MCPcopy Index your code
hub / github.com/neetcode-gh/leetcode / removeKdigits

Method removeKdigits

java/0402-remove-k-digits.java:2–30  ·  view source on GitHub ↗
(String num, int k)

Source from the content-addressed store, hash-verified

1class Solution {
2 public String removeKdigits(String num, int k) {
3 if(k >= num.length())
4 return "0";
5
6 Stack<Character> stack = new Stack<>();
7 for(char d: num.toCharArray()){
8 while(!stack.empty() && d < stack.peek() && k > 0){
9 stack.pop();
10 k--;
11 }
12 stack.push(d);
13 }
14 while(!stack.empty() && k > 0){
15 stack.pop();
16 k--;
17 }
18
19 StringBuilder res = new StringBuilder();
20 while(!stack.empty()){
21 res.insert(0, stack.pop());
22 }
23
24 for(int i = 0; i < res.length(); i++){
25 if(res.charAt(i) != '0'){
26 return res.toString().substring(i, res.length());
27 }
28 }
29 return "0";
30 }
31}

Callers

nothing calls this directly

Calls 6

emptyMethod · 0.45
peekMethod · 0.45
popMethod · 0.45
pushMethod · 0.45
insertMethod · 0.45
toStringMethod · 0.45

Tested by

no test coverage detected