402. Remove K Digits

Description

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 10002 and will be ≥ k.
  • The given num does not contain any leading zero.

Example 1:

Input: num = "1432219", k = 3
Output: "1219"
Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.

Example 2:

Input: num = "10200", k = 1
Output: "200"
Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.

Example 3:

Input: num = "10", k = 2
Output: "0"
Explanation: Remove all the digits from the number and it is left with nothing which is 0.

Solution

Greedy & Stack, time O(n), space O(n)

假设num的组成是"abc.....",如果删掉'a',那么剩下的是"bc....",一定是由b打头;如果删掉任何a之后的字符,剩下的string必定由a打头。于是比较a和b的大小即可,用Greedy的思路选择最优解即可。

注意需要考虑a = b的情况,在这种情况下需要先遍历到后面的元素才知道怎么处理a和b(考虑"223"和"221"),所以用Stack来实现就显得很合理了。

class Solution {
    public String removeKdigits(String num, int k) {
        if ("0".equals(num) || k < 1) {
            return num;
        }
        
        Stack stack = new Stack<>();
        for (char c : num.toCharArray()) {
            // whenever meet a digit which is less than the previous digit, 
            // discard the previous one to keep chars in stack are in asc order
            while (k > 0 && !stack.empty() && stack.peek() > c) {
                stack.pop();
                --k;
            }
            
            if (stack.empty() && c == '0') {    // discard '0' at the head
                continue;
            }
            
            stack.push(c);
        }
        
        while (!stack.empty() && k-- > 0) {     // corner case "1234", 2
            stack.pop();
        }
        
        StringBuilder sb = new StringBuilder();
        while (!stack.empty()) {
            sb.insert(0, stack.pop());  // construct number
        }
        
        return sb.length() == 0 ? "0" : sb.toString();
    }
}

你可能感兴趣的:(402. Remove K Digits)