Easy understand but a bit longer Java


  • 0
    C
     public static String removeKdigits(String num, int k) {
    	        if(k >= num.length()) return "0";
    	        if(k == 0) return num;
    	        StringBuilder sb = new StringBuilder();
    	        helper(num,k,  sb);
    	        int remove = 0;
    	        for(int i = 0; i < sb.length(); i++){
    	        	if(sb.charAt(i) == '0')  remove++;
    	        	else{
    	        		break;
    	        	}
    	        }
    	        String res  = sb.substring(remove,sb.length());
    	        if(res.length() == 0) res = "0";
    	        return res;
    	        
    	    }
    	    private static void helper(String num, int k , StringBuilder sb){
    	        if(k == 0) {
    	        	sb.append(num);
    	        	return;
    	        }
    	        if(num.length() <= k) return;
    	        int minIndex = 0;
    	        for(int i = 1; i <= k; i++){
    	            if(num.charAt(i)-'0' < num.charAt(minIndex)-'0'){
    	                minIndex = i;
    	            }
    	        }
    	        sb.append(num.charAt(minIndex));
    	        num = num.substring(minIndex+1, num.length());
    	        helper(num, k-minIndex, sb);
    	    }

Log in to reply
 

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