LeetCode/solutions/402. Remove K Digits.md
2022-11-07 22:17:10 +08:00

38 lines
1.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [402. Remove K Digits](https://leetcode.cn/problems/remove-k-digits/)
# 思路
要求返回的数字最小,其实就是字典序最小,所以类似[316. Remove Duplicate Letters](https://leetcode.cn/problems/remove-duplicate-letters/):需要**尽可能把小数字放在前面**,所以需要找到满足 num[i]>num[i+1],然后去掉 num[i],即单调栈。
具体的维护一个初始为空的最终结果字符串stk并遍历一遍num
1对于当前字符 c如果stk结尾字符比c大说明找到了 num[i]>num[i+1]即应该去掉skt结尾字符并k--,然后继续判断直到不满足;
2将c加入stk
注意最后需要处理k还大于0以及前导0。
关键词:单调栈
# C++
```C++
class Solution {
public:
string removeKdigits(string num, int k) {
if(num.size() <= 1) return "0";
string stk = "";
for(char c: num){
while(!stk.empty() && k > 0 && c < stk.back()){
k--;
stk.pop_back();
}
stk.push_back(c);
}
for(int i = 0; i < k; i++) stk.pop_back();
int lead_0_cnt = 0;
for(char c: stk){
if(c != '0') break;
else lead_0_cnt++;
}
return lead_0_cnt == stk.size() ? "0" : stk.substr(lead_0_cnt);
}
};
```