share my straight java solution by stack


  • 0
    C
    public String removeKdigits(String num, int k) {
        char[] array = num.toCharArray();
        Stack<Character> stack = new Stack<>();
        //avoid travel empty-stack
        stack.push('0');
        //remove non-decresing element one by one
        for (int i = 0; i < array.length; ) {
        	char top = stack.peek();
    		if(top > array[i] && k > 0){
    			stack.pop();
    			k--;
    		}
    		else{
    			stack.push(array[i]);
    			i++;
    		}
    	}
    	//remove some stack top elments if k != 0
        while(k-- > 0 && !stack.isEmpty()){
        	stack.pop();
        }
        StringBuilder ret = new StringBuilder();
        boolean findNonZero = false;
        //crete result and ignore leading-zero
        for(char c : stack){
        	if(c != '0') findNonZero = true;
        	if(findNonZero) ret.append(c);
        }
        //note corner case: length = 0
        return ret.length() == 0 ? "0" : ret.toString();
    }

Log in to reply
 

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