美文网首页
402. Remove K Digits

402. Remove K Digits

作者: matrxyz | 来源:发表于2018-01-16 13:28 被阅读0次

    http://www.cnblogs.com/grandyang/p/5883736.html
    https://leetcode.com/problems/remove-k-digits/discuss/88660

    Solution:

    思路:

    Time Complexity: O(N) Space Complexity: O(N)

    Solution Code:

    public class Solution {
        public String removeKdigits(String num, int k) {
            int digits = num.length() - k;
            char[] stk = new char[num.length()];
            int top = 0;
            // k keeps track of how many characters we can remove
            // if the previous character in stk is larger than the current one
            // then removing it will get a smaller number
            // but we can only do so when k is larger than 0
            for (int i = 0; i < num.length(); ++i) {
                char c = num.charAt(i);
                while (top > 0 && stk[top-1] > c && k > 0) {
                    top -= 1;
                    k -= 1;
                }
                stk[top++] = c;
            }
            // find the index of first non-zero digit
            int idx = 0;
            while (idx < digits && stk[idx] == '0') idx++;
            return idx == digits? "0": new String(stk, idx, digits - idx);
        }
    }
    

    相关文章

      网友评论

          本文标题:402. Remove K Digits

          本文链接:https://www.haomeiwen.com/subject/zzjsoxtx.html