Java Solution without using Stack


  • 0
    H
    public class Solution {
        public String removeKdigits(String num, int k) {
            num = removeZero(num);
            if (k == 0) return num.length() == 0 ? "0" : num;
            if (num.length() <= k) return "0";
    
            for (int i = 1; i <= k; i ++) {
                if (num.charAt(i) == '0') {
                    return removeKdigits(num.substring(i), k - i);
                }
            }
            
            int index = 0;
            for (int i = 1; i < num.length(); i ++) {
                if (num.charAt(i) >= num.charAt(i-1)) index = i;
                else break;
            }
            String min = num.substring(0, index) + num.substring(index+1);
            
            return removeKdigits(min, k-1);
        }
        
        private String removeZero(String num) {
            int start = 0;
            while (start < num.length()) {
               if (num.charAt(start) == '0') start ++;
               else break;
            }
            return num.substring(start);
        }
    }
    

Log in to reply
 

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