From d36220bd1dadba197ea7b4090af2d4e141930d95 Mon Sep 17 00:00:00 2001 From: ShusenTang Date: Mon, 7 Nov 2022 22:17:10 +0800 Subject: [PATCH] add 402 --- README.md | 1 + solutions/402. Remove K Digits.md | 38 +++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 solutions/402. Remove K Digits.md diff --git a/README.md b/README.md index ffb2257..0a06129 100644 --- a/README.md +++ b/README.md @@ -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| | diff --git a/solutions/402. Remove K Digits.md b/solutions/402. Remove K Digits.md new file mode 100644 index 0000000..b0efdf7 --- /dev/null +++ b/solutions/402. Remove K Digits.md @@ -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); + } +}; +``` \ No newline at end of file