All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0401_0500.s0402_remove_k_digits.Solution Maven / Gradle / Ivy

There is a newer version: 1.37
Show newest version
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);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy