Home LeetCode - 402. Remove K Digits
Post
Cancel

LeetCode - 402. Remove K Digits

402. 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.

제한사항

  • The length of num is less than 10002 and will be ≥ k.
  • The given num does not contain any leading zero.

입출력 예

1
2
3
4
5
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.
1
2
3
4
5
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.
1
2
3
4
5
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.

풀이

  • Greedy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
    string removeKdigits(string num, int k) {
        string answer;
        int index = 0;

        answer.push_back(num[0]);
        for(auto i = 1 ; i < num.size() && k >= 0 ; ++i){
            while(!answer.empty() && answer.back() - '0' > num[i] - '0' && k > 0){
                answer.pop_back();
                --k;
            }
   
            answer.push_back(num[i]);
        }
        
        for( ; answer.size() && k > 0 ; --k)
            answer.pop_back();
        
        size_t first_not_zero = answer.find_first_not_of('0');
        return (first_not_zero == string::npos) ? "0" : answer.substr(first_not_zero);
    }
};
This post is licensed under CC BY 4.0 by the author.