从中看出一个东西, 凡是这种要跟上一个digit比较,并且就只是上一个digit的题型,用stack很方便; 也就是解法中的第二部分的while

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

        // prev larger: discard prev
        while (i < len) {
            while (k > 0 && !st.empty() && st.peek() > num.charAt(i)) {
                st.pop();
                k--;
            }
            st.push(num.charAt(i));
            i++;
        }

        // k != 0, stack: greater at top; pop all top K digits
        while (k > 0) {
            st.pop();
            k--;
        }

        // build res from stack
        StringBuilder sb = new StringBuilder();
        while (!st.empty()) {
            sb.append(st.pop());
        }
        sb.reverse();

        while (sb.length() > 1 && sb.charAt(0) == '0') {
            sb.deleteCharAt(0);
        }
        return sb.toString();
    }

另外, StringBuilder的用法要弄熟