每日一题- Leetcode 402. Remove K Digits

Posted yy0506

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了每日一题- 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/

 

以上是关于每日一题- Leetcode 402. Remove K Digits的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 每日一题 953. 验证外星语词典

Leetcode每日一题(3)

LeetCode每日一题

LeetCode2022 7月 每日一题

LeetCode2022 7月 每日一题

LeetCode9月 每日一题