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

I have learnt a lot from these algorithms especially from the way people think and I think that’s the fun of solving algorithm questions.

--

--

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