Note:

1. Find a increasing digits number. It's kind of longest increasing subsequence but with fixed size.

2. Remember to remove the zeros from beginning.

class Solution {
    public String removeKdigits(String num, int k) {
        if (num.length() == 0) return "0";
        int i = 1;
        Stack<Character> stack = new Stack<>();
        stack.push(num.charAt(0));
        while (i < num.length()) {
            while (k > 0 && !stack.isEmpty() && num.charAt(i) < stack.peek()) {
                k--;
                stack.pop();
            }
            stack.push(num.charAt(i++));
        }
        
        while (k > 0 && !stack.isEmpty()) {
            stack.pop();
            k--;
        }
        StringBuilder result = new StringBuilder();
        while (!stack.isEmpty()) {
            result.insert(0, stack.pop());
        }
        while (result.length() > 1 && result.charAt(0) == '0') result.deleteCharAt(0);
        return result.length() == 0 ? "0" : result.toString();
    }
}

 

posted on 2017-10-08 16:24  keepshuatishuati  阅读(109)  评论(0编辑  收藏  举报