My accept Java solution use stack


  • 0
    S
    public String removeKdigits(String num, int k) {
            char[] cs = num.toCharArray();
    	Stack<Character> stack = new Stack<>();
    	StringBuilder sb = new StringBuilder();
    	for (int i = 0; i < cs.length; i++) {
    		while (k>0 && !stack.isEmpty() && cs[i]-stack.peek() < 0 ) {
    			stack.pop();
    			k--;
    		}
    		stack.push(cs[i]);
    		if (k <= 0){
    			sb.append(num.subSequence(i+1, num.length()));
    			break;
    		}
    	}
    	while (k-- > 0) stack.pop();
    	while (!stack.isEmpty()) sb.insert(0, stack.pop());
    	while (sb.length()>0 && sb.charAt(0) == '0') sb.deleteCharAt(0);
    	return sb.length() == 0 ? "0" : sb.toString();
        }
    

Log in to reply
 

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