mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
38 lines
1.3 KiB
Markdown
38 lines
1.3 KiB
Markdown
![]() |
# [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);
|
|||
|
}
|
|||
|
};
|
|||
|
```
|