Java with stack, get rid of prefix "0"s inside the loop.


  • 0
    N
    public class Solution {
        public String removeKdigits(String num, int k) {
            if(num == null || num.length() == 0) return num;
            if(k>=num.length()) return "0";
            
            Stack<Integer> s = new Stack<>();
            StringBuilder sb = new StringBuilder();
            for(char c: num.toCharArray()){
                int cur = c-'0';
                if(s.size() == 1 && s.peek() == 0){
                    s.pop();
                }
                while(!s.isEmpty() && k>0 && s.peek()>cur){
                    s.pop();
                    k--;
                }
                s.push(cur);
            }
            
            while(k>0){
                s.pop();
                k--;
            }
            
            while(!s.isEmpty()) 
                sb.insert(0,s.pop());
            
            return sb.toString();
        }
    }
    
    
    

Log in to reply
 

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