My Ugly Solution :(


  • 0
    public String removeKdigits(String num, int k) {
    	if(num.isEmpty() || num.length()==k) return "0";
    	char[] chars = num.toCharArray();
    	Deque<Character> stack = new ArrayDeque<>();
    	StringBuilder sb = new StringBuilder();
    	for(int i=0;i<chars.length;i++) {
    		char c = chars[i];
    		while((!stack.isEmpty()) && k>0 && stack.peek()>c) {
    			stack.pop();
    			k--;
    		}
    		if((!stack.isEmpty()) && k>0 && chars.length-i<=k) {
    			c = stack.pop();
    			k--;
    		}
    		stack.push(c);
    	}
    	while(!stack.isEmpty()) {
    		sb.insert(0,stack.pop());
    	}
    	String trimmedString = sb.toString().replaceFirst("^0+", "");
    	return trimmedString.length()>0?trimmedString:"0";
    }
    

Log in to reply
 

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