Clean Java Code


  • 0
    A
    public String removeKdigits(String num, int k) {
    	Stack<Integer> st = new Stack<Integer>();
    	int i = 0;
    	while (i < num.length()) {
    		while (!st.isEmpty() && st.peek() > (num.charAt(i) - '0') && k > 0) {
    			st.pop();
    			k--;
    		}
    		st.push(num.charAt(i) - '0');
    		i++;
    	}
    	StringBuilder sb = new StringBuilder();
    	while (!st.isEmpty())
    		sb.append((char) (st.pop() + '0'));
    	String res = sb.reverse().toString().substring(0, sb.length() - k);
    	while (res.length() > 0 && res.charAt(0) == '0')
    		res = res.substring(1);
    	return res.isEmpty() ? "0" : res;
    }

Log in to reply
 

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