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

problem description
public static String removeKdigits(String num, int k) {
Stack<Character> stack = new Stack<>();
StringBuilder answer = new StringBuilder();
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()) {
answer.append(stack.pop());
}

if (!answer.toString().isEmpty()) {
answer = answer.reverse();
String s = answer.toString().replaceFirst("^0+(?!$)", "");
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();
}

OBSERVATION

--

--

--

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

Recommended from Medium

Adding .env file support to a legacy PHP project

A Simple (But Comprehensive) Guide on Updating Your System Bios

Java — How to dynamically compile and load external java classes | Code Factory

What I learned Dec 14th — Dec 20th

Pumping Lemma for CFL and Applications

Our Response to COVID-19

Send unlimited WhatsApp messages for free using Python

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Chunks

Chunks

More from Medium

How to rotate image (matrix) to 90° in-place using O(n) time

Leetcode 862. Shortest Subarray with Sum at Least K

Kruskal’s Algorithm — A Summary