leetcode402 - Remove K Digits - medium

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.

 

递增栈的思路,相当于栈里从下到上维护最后的结果,当前数字要是小于栈顶了开始逐一pop比它大的,也就是确保当前这一位越小越好,因为栈越下面越是高位。
也可以不用特意开个stack,直接用最后的结果str当做栈来维护就行,反正能pop_back。
 
细节:
1. 如果此时str是空的,又刚好碰到‘0’,就不要push了,避免0开头的情况
2. 遍历一遍结束,如果还没删掉k个字符,在str不为空的条件下要继续删
3. 最后要check一下str是否为空
 
实现:
class Solution {
public:
    string removeKdigits(string num, int k) {
        
        string res;
        
        for (char c : num) {
            while (!res.empty() && res.back() > c && k > 0) {
                res.pop_back();
                k--;
            }
            if (res.empty() && c == '0') continue;
            res.push_back(c);
        }
        
        while (k > 0 && !res.empty()){
            res.pop_back();
            k--;
        }
        
        return res.empty() ? "0" : res;
        
    }
};

 

你可能感兴趣的:(leetcode402 - Remove K Digits - medium)