Easy Java Solution


  • 0
    K
    public String removeKdigits(String num, int k) {
        if (num == null || num.length() == 0 || k >= num.length())
            return "0";
        if (k == 0)
            return num;
        StringBuilder sb = new StringBuilder(num);
        int i = 0;
        while (i < k) {
            removeNextChar(sb);
            i++;
        }
        while (sb.length() > 0 && sb.charAt(0) == '0')
            sb.deleteCharAt(0);
        return sb.length() == 0 ? "0" : sb.toString();
    }
    
    private void removeNextChar(StringBuilder sb) {
        int cur = 0;
        while (cur < sb.length() - 1 && sb.charAt(cur) <= sb.charAt(cur+1)) {
            cur++;
        }
        sb.deleteCharAt(cur);
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.