Share my Java Solution, beat 92%!


  • 0
    C
    public class Solution {
        public String removeKdigits(String num, int k) {
              if(k==0) return num;
              
              int n=num.length();
              char[] res=new char[n-k];
              int j=0;
              for(int i=0;i<n;i++){
                  while(j>0&&n-i+j>n-k&&res[j-1]>num.charAt(i)){
                      j--;
                  }
                  if(j<n-k){
                     res[j++]=num.charAt(i);
                  }
              }
             //return String.valueOf(res);          
              StringBuilder strbuild=new StringBuilder();
              int i=0;
              for(;i<res.length;i++){
                  if(res[i]!='0'){
                      break;
                  }
              }
              while(i<res.length){
                  strbuild.append(res[i]);
                  i++;
              }
              return strbuild.length()!=0?strbuild.toString():"0";
        }
        
    }
    
    ···

Log in to reply
 

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