Java solution


  • 0
    H
    public String removeKdigits(String num, int k) {
            if (num.length() == k) {
            	return "0";
            }
            int count = 0;
            StringBuilder sb = new StringBuilder();
            for (char c : num.toCharArray()) {
            	while (sb.length() != 0 && sb.charAt(sb.length() - 1) > c && count < k) {
            		sb.deleteCharAt(sb.length() - 1);
            		++count;
            	}
            	if (c != '0' || sb.length() != 0) 
            		sb.append(c);
            }
            if (sb.length() == 0) {
            	return "0";
            }
            return sb.substring(0, sb.length() - k + count); // if the deletion is not reach k,remove the rest (k - count);
    }
    
    

Log in to reply
 

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