【Leetcode】402. Remove K Digits

题目链接:https://leetcode.com/contest/5/problems/remove-k-digits/

题目:
Given a non-negative integer num represented as a string, remove k digits from the number so that the new number is the smallest possible.

Note:
The length of num is less than 105 and will be ≥ k.
The given num does not contain any leading zero.

思路:
http://blog.csdn.net/yeqiuzs/article/details/52496818

跟这题类似,用栈实现 获取 某字符串 被删除 一些字符后 能得到的最小 最小字典序(大小)的关系。最后~~本次contest只做出这三题,这里写图片描述

罚时80minutes

算法:

    public String removeKdigits(String num, int k) {
        Stack<Integer> stack = new Stack<Integer>();
        if (num.length() == 0 || num.length() <= k)
            return "0";

        for (int i = 0; i < num.length(); i++) {
            int cur = num.charAt(i) - '0';
            while (!stack.isEmpty() && cur < stack.peek()
                    && num.length() - i - 1 >= (num.length() - k) - stack.size()) {
                stack.pop();
            }
            if (stack.size()<num.length()-k)
                stack.push(cur);
        }

        StringBuilder res = new StringBuilder();
        while (!stack.isEmpty())
            res.insert(0, stack.pop());

        while (res.length() > 0 && res.charAt(0) == '0')
            res.deleteCharAt(0);

        if (res.length() == 0)
            return "0";
        return res.toString();
    }

你可能感兴趣的:(leetcode,Leetcode题解java版)