402. Remove K Digits
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.
方法1: monotonic stack
水中的鱼:http://fisherlei.blogspot.com/2017/07/leetcode-remove-k-digits-solution.html
思路:
易错点:
- 如果string本身为increasing序列,单调栈算法是舍不掉任何数的:最后要再检查一下有没有将k个数字除干净,如果没有,我们已知结果是个单调数,从后面开始pop较大值。
- 最后要去掉前缀0。
- 如果为空返回“0”。
- 单调栈算法再pop的时候一定要随时查空。
class Solution {
public:
string removeKdigits(string num, int k) {
// if need to remove all
if (k == num.size()) {
return "0";
}
stack<char> stk;
for (char c : num) {
// keep popping while having better choice
// maintain an increasing sequence in the stack
while (k && !stk.empty() && stk.top() > c) {
stk.pop();
k--;
}
stk.push(c);
}
// if haven't used up the k,delete from the end (large ones)
// corner case like "1111"
while (k) {
stk.pop();
k--;
}
// construct the number from the stack
string ans;
while (!stk.empty()) {
ans += stk.top();
stk.pop();
}
//remove all the 0 at the head
while (ans.size() > 1 && ans.back() == '0') {
ans.pop_back();
}
reverse(ans.begin(), ans.end());
return ans;
}
};
grandyang: https://www.cnblogs.com/grandyang/p/5883736.html
class Solution {
public:
string removeKdigits(string num, int k) {
string result = "";
int n = num.size(), keep = n - k;
for (char c : num) {
while (k && result.size() && result.back() > c) {
result.pop_back();
k--;
}
result.push_back(c);
}
result.resize(keep);
while (!result.empty() && result[0] == '0')
result.erase(result.begin());
return result.empty() ? "0" : result;
}
};
二刷:
class Solution {
public:
string removeKdigits(string num, int k) {
string res = "";
for (char c: num) {
while (k > 0 && res.size() && res.back() > c) {
res.pop_back();
k--;
}
res.push_back(c);
}
while (k-- > 0) res.pop_back();
while (!res.empty() && *res.begin() == '0') res.erase(res.begin());
return res.empty() ? "0" : res;
}
};