Come from : [https://leetcode-cn.com/problems/remove-k-digits/]
402. Remove K Digits
1.Question
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:
1. The length of num is less than 10002 and will be ≥ k.
2. 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.
2.Answer
meduim 类型题目。贪心算法。
算法分析:
- 使用栈存储最终结果或删除工作,从高位向低位遍历num。
- 如果遍历的数字大于栈顶元素,则将该数字push入栈。
- 如果小于栈顶元素则进行pop弹栈,知道栈为空或者不能删除数字(k==0)或栈顶小于当前元素为止。
弹出示例:
思考,需要特殊处理的部分:(特殊处理的部分全部在AC代码中给出)
- 当所有数字都扫描完成后,k仍然>0,应该如何处理?比如:num=12345,k=3时
- 当数字中有0出现,应该有怎样的特殊处理?比如:num=100200,k=0时
- 如何将最后结果存储为字符串并返回?
AC代码如下:
class Solution {
public:
string removeKdigits(string num, int k) {
vector<int> S;
string result = ""; //存储最终结果
for(int i = 0; i < num.length(); ++i)
{
int number = num[i] - '0';