mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
add 402
This commit is contained in:
parent
2943dbfc91
commit
d36220bd1d
@ -287,6 +287,7 @@ My LeetCode solutions with Chinese explanation. 我的LeetCode中文题解。
|
||||
| 397 |[Integer Replacement](https://leetcode.com/problems/integer-replacement/)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/397.%20Integer%20Replacement.md)|Medium| |
|
||||
| 398 |[Random Pick Index](https://leetcode.com/problems/random-pick-index/)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/398.%20Random%20Pick%20Index.md)|Medium| |
|
||||
| 400 |[Nth Digit](https://leetcode.com/problems/nth-digit)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/400.%20Nth%20Digit.md)|Medium| |
|
||||
| 402 |[Remove K Digits](https://leetcode.cn/problems/remove-k-digits/)|[C++](solutions/402.%20Remove%20K%20Digits.md)|Medium| |
|
||||
| 404 |[Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/404.%20Sum%20of%20Left%20Leaves.md)|Easy| |
|
||||
| 405 |[Convert a Number to Hexadecimal](https://leetcode.com/problems/convert-a-number-to-hexadecimal)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/405.%20Convert%20a%20Number%20to%20Hexadecimal.md)|Easy| |
|
||||
| 406 |[Queue Reconstruction by Height](https://leetcode.com/problems/queue-reconstruction-by-height/)|[C++](solutions/406.%20Queue%20Reconstruction%20by%20Height.md)|Medium| |
|
||||
|
38
solutions/402. Remove K Digits.md
Normal file
38
solutions/402. Remove K Digits.md
Normal file
@ -0,0 +1,38 @@
|
||||
# [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);
|
||||
}
|
||||
};
|
||||
```
|
Loading…
Reference in New Issue
Block a user