g0401_0500.s0402_remove_k_digits.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java Show documentation
Show all versions of leetcode-in-java Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g0401_0500.s0402_remove_k_digits;
// #Medium #String #Greedy #Stack #Monotonic_Stack
// #2022_07_15_Time_4_ms_(99.66%)_Space_42.3_MB_(99.36%)
public class Solution {
public String removeKdigits(String num, int k) {
char[] list = new char[num.length()];
int len = num.length() - k;
int top = 0;
for (int i = 0; i < num.length(); i++) {
while (top > 0 && k > 0 && num.charAt(i) < list[top - 1]) {
top--;
k--;
}
list[top++] = num.charAt(i);
}
int number = 0;
while (number < len && list[number] == '0') {
number++;
}
return number == len ? "0" : new String(list, number, len - number);
}
}