# I didn’t know how to solve this Leetcode Problem!😭😭😭

public static String removeKdigits(String num, int k) {
Stack<Character> stack = new Stack<>();
if (num.length() == k) return "0";

for (int i = 0; i < num.length(); i++) {
while (k > 0 && !stack.isEmpty() && stack.peek() > num.charAt(i)) {
stack.pop();
k = k - 1;
}
stack.push(num.charAt(i));
}

while (!stack.isEmpty()) {
}

if (k != 0)
s = s.substring(0, answer.length() - k);
return s;
} else
return "0";
}
public static String  removeKdigits(String num, int k) {
Stack<Character> stack = new Stack<>();
int length = num.length();
for (int i = 0; i < length; i++) {
while (!stack.isEmpty() && k > 0 && stack.peek() > num.charAt(i)) {
stack.pop();
k -= 1;
}

if (!stack.isEmpty() || num.charAt(i) != '0')
stack.push(num.charAt(i));
}

//Now remove the largest values from the top of the stack
while (!stack.empty() && k != 0) {
stack.pop();
k--;
}

if (stack.isEmpty())
return "0";

//now retrieve the number from stack into a string
StringBuilder result = new StringBuilder();
while (!stack.isEmpty()) {
result.append(stack.pop());
}
return result.reverse().toString();
}

--

--

--

## More from Chunks

Love podcasts or audiobooks? Learn on the go with our new app.