Given a non-negative integer num represented as a string, remove kdigits 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.
/* 从string 去掉k位使剩余的数最小
* 单调栈: 保证最高位最小, 最低位最大 这明显是要得到一个单调递增序列
*
* 返回的结果 (单调栈部分)(剩余部分) 前面高位最小保证了最后返回的结果最小
* 然后出栈的次数等于k时代表已经删除了k位(此后把剩余的依次push进来即可)
*
* 注意最后还要进行头部去0操作
* */
class Solution {
public:
string removeKdigits(string num, int k) {
if(num.size() == k) return "0";
string monoret; // 单调栈 在出栈k次后不再保证单调性
int cnt=k; // 记录出栈次数
for(char &val:num){
while(!monoret.empty() && cnt>0 && val<monoret.back()){
cnt--;
monoret.pop_back();
}
monoret.push_back(val);
}
// monoret eg: (001234)548379
int pos=0;
while(monoret[pos]=='0') pos++;
// 注意最后可能 1.首部全为零 monoret为空 2.num是1234这种 即中间没有进行出栈操作 全部记录到了ret中, 这时要取len-k这么长的长度
monoret = monoret.substr(pos, num.size()-k-pos);
return monoret.empty()? "0" : monoret;
}
};