扫一遍就可以的

没有什么花哨技巧,扫一遍加一些处理就可以做出来的

Remove K Digits

Given a non-negative integer num represented as a string, remove k digits from the number so that the new number is the smallest possible.

思路: 让字符串保持一个递增的顺序

public class Solution {
    public String removeKdigits(String num, int k) {
        // let digits have increasing order
        if(num.length() == k) {
            return "0";
        }

        StringBuilder sb = new StringBuilder(num);
        for(int i = 0; i < k; i++) {
            int j = 0;
            while (j < sb.length() - 1 && sb.charAt(j) <= sb.charAt(j + 1)) {
                j++;
            }
            sb.delete(j, j + 1);
        }

        // remove leading 0s
        while(sb.length() > 1 && sb.charAt(0) == '0') {
            sb.deleteCharAt(0);
        }

        if(sb.length() == 0) {
            return "0";
        }

        return sb.toString();
    }
}

results matching ""

    No results matching ""