Easy understanding Java solution


  • 0
    D
    public class Solution {
        public String removeKdigits(String num, int k) {
           if(num==null||num.length()==0) return "";
           int len=num.length();
           len-=k;
           if((num.charAt(0)=='0'&&len==1)||len==0) return "0";
           Stack<Character> s=new Stack<>();
           for(int i=0;i<num.length();i++){
               char c=num.charAt(i);
               while(!s.isEmpty()&&c<s.peek()&&s.size()-1+num.length()-i>=len) s.pop();
               if(s.size()==len&&num.charAt(i)==num.charAt(i-1)) continue;
               if(s.size()<len) s.push(c);
           }
           StringBuilder sb=new StringBuilder();
           while(!s.isEmpty()) sb.insert(0,s.pop());
           String str=sb.toString();
           while(str.startsWith("0")&&str.length()>1) str=str.substring(1);
           return str;
        }
    }
    

Log in to reply
 

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