【每日一题】- Leetcode 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.


Intuition:

1. leftmost distinct digits that determine the superior of the two numbers, e.g. for A=1axxx, B=1bxxx, if the digits a > b, then A > B. So when removing the digits, iterate from the left to right.

2. How to eliminate digits?

Every time comparing the current digit and its left digit, if the left one is larger, eliminate this larger left one. 

3. Implementation: stack data structure

4. Solution:

class Solution {
    public String removeKdigits(String num, int k) {
        Stack<Character> s = new Stack<>();
        for (int i = 0; i < num.length(); i++) {
            while (!s.isEmpty() && s.peek() > num.charAt(i) && k > 0) {
                s.pop();
                k--;
            }
            s.push(num.charAt(i));
        }
        
        //remove the remaining digits from the tail
        while (k > 0) {
            s.pop();
            k--;
        }
        
        //build the final string, while removing the leading zeros
        boolean leadingZero = true;
        String ans = "";
        for (char digit : s) {
            if (leadingZero && digit == '0') continue;
            leadingZero = false;
            ans += digit;
        }
        
        
        if (ans.length() == 0) return "0";
        return ans;
    }
}

  

Reference: https://leetcode.com/problems/remove-k-digits/solution/

猜你喜欢

转载自www.cnblogs.com/yy0506/p/12887597.html