Very straightforward solution uses Stack --- Java


  • 0
    M
    public class Solution {
        public String removeKdigits(String num, int k) {
            Stack<Integer> stack = new Stack<Integer>();
            stack.push(0);
            for(int i = 0; i < num.length(); i++){
                int digit = num.charAt(i) - '0';
                while(!stack.isEmpty() && stack.peek() > digit && k > 0){
                    stack.pop();
                    k--;
                }
                stack.push(digit);
            }
            while(k > 0){
               stack.pop();
               k--;
            }
            StringBuilder res = new StringBuilder();
            while(!stack.isEmpty()){
                res.insert(0, stack.pop());
            }
            int index = 0;
            while(index < res.length() && res.charAt(index) == '0'){
                index++;
            }
            if(index == res.length()){
                return "0";
            }
            return res.toString().substring(index);
        }
    }

Log in to reply
 

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