5 lines Java


  • 0
    W

    The idea is from the question <Create Maximum Number>

    public String removeKdigits(String num, int k) {
        StringBuilder sb = new StringBuilder(num);
        for (int idx = 0; k-- > 0 && sb.length() > 0; sb.deleteCharAt(idx))
            if ((idx = Math.min(sb.length() - 1, idx)) > 0 && sb.charAt(idx - 1) > sb.charAt(idx)) --idx;
            else for (int end = sb.length() - 1; idx < end && sb.charAt(idx) <= sb.charAt(idx + 1); idx++);
        return sb.length() == 0 ? "0" : new BigInteger(sb.toString()).toString();
    }
    

    Cause the oj throws "unreachable statement" exception for importing class BigInteger, I write a 6 lines version.

    public String removeKdigits(String num, int k) {
        StringBuilder sb = new StringBuilder(num);
        for (int idx = 0; k-- > 0 && sb.length() > 0; sb.deleteCharAt(idx)) // delete char 
            if ((idx = Math.min(sb.length() - 1, idx)) > 0 && sb.charAt(idx - 1) > sb.charAt(idx)) --idx;
            else for (int end = sb.length() - 1; idx < end && sb.charAt(idx) <= sb.charAt(idx + 1); idx++);
        for (k = 0; k < sb.length() && sb.charAt(k) == '0'; k++); // skip leading zeros
        return k == sb.length() ? "0" : sb.substring(k);
    }
    

Log in to reply
 

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