An easy understanding Java Solution


  • 0
    C
       
        public String removeKdigits(String num, int k) {
            if (k <= 0) return num;
            if(k >= num.length()) return "0";
            StringBuilder sb = new StringBuilder(num);
            while (k-- > 0) {
                for (int i = 1; i < sb.length(); i++) {
                    //find the first peek, or the last to delete
                    if (sb.charAt(i) < sb.charAt(i - 1)) {
                        sb.deleteCharAt(i-1);
                        break;
                    }
                    if(i == sb.length() - 1){
                        sb.deleteCharAt(i);
                    }
                }
            }
            while (sb.length() > 0 && sb.charAt(0) == '0') sb.deleteCharAt(0);
            if(sb.length() == 0) return "0";
            return sb.toString();
        }
    

    An Optimized Solution

    public String removeKdigits(String num, int k) {
            if (k <= 0) return num;
            if (k >= num.length()) return "0";
            StringBuilder sb = new StringBuilder(num);
            
            for (int i = 1; i < sb.length(); ) {
                if(sb.charAt(i) < sb.charAt(i-1)){
                    sb.deleteCharAt(i-1);
                    i = i > 1 ? i - 1 : 1;
                    if(--k <= 0) break;
                }else if(i == sb.length() - 1){
                    sb.delete(i - k + 1, i + 1);
                    break;
                }else{
                    i++;
                }
            }
            while (sb.length() > 0 && sb.charAt(0) == '0') sb.deleteCharAt(0);
            if (sb.length() == 0) return "0";
            return sb.toString();
        }
    

Log in to reply
 

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