leetcode402. Remove K Digits【单调栈变形】
来源:互联网 发布:mac删除软件 编辑:程序博客网 时间:2024/06/01 10:21
Given a non-negative integer num represented as a string, remove k digits 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 = 3Output: "1219"Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.
Example 2:
Input: num = "10200", k = 1Output: "200"Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.
Example 3:
Input: num = "10", k = 2Output: "0"Explanation: Remove all the digits from the number and it is left with nothing which is 0.
Subscribe to see which companies asked this question.
Show Similar Problems
题意:从一个字符串中删除k个字母,使得剩余的数字最小
注意,如果将0前面的数字删除,已相当于删除了0
举个例子 1070934 k=2
由于刚刚说的这个问题,导致我傻乎乎的想用结构体{原来位置,以0分割的数字}来存储
然鹅……并不需要……
看到标签中有“栈”就想到一定是单调栈的应用,开始想到用在单调栈存储答案,后来又想到用单调栈存储不要的字符……反正就是卡在了0的处理上,之前的做法实现太tm的难了
我们来想一想“单调栈”是啥,维护一个单调的集合,后进先出
对于这个题来说呢,恰好就能解决0的处理问题,因为要是遇到0就把之前的都弹出去了啊!最终的集合中只有前面有0,特殊处理一下就好啦
还是上一个例子:
最终在栈中的是00934,完美的解决了以0分割的问题,因为0出现一定会把前面的非0数字挤出去,然后0剩在栈中,还不算删掉的数字个数里面
牵强的想想为啥这么做
如果删除数字,一定是会优先选择前面&&大的数字,前面&&小的数字是要保留下来的,所以想到是单调栈维护;
想到00934的“0”其实是没有被删除的,所以也不用真的把它删除掉,留到最后就好啦
class Solution {public: string removeKdigits(string num, int k) { string ans; int n=k,len=num.size(); for(auto val:num) { while(n>0&&!ans.empty()&&val<ans.back()) { n--; ans.pop_back(); } ans.push_back(val); } int pos=0; while(ans[pos]=='0') pos++; if(pos==len-k||k==len)return "0"; else { ans=string(ans,pos,len-k-pos); return ans; } }};
阅读全文
0 0
- leetcode402. Remove K Digits【单调栈变形】
- [LeetCode402]Remove K Digits
- Leetcode402——Remove K Digits
- 402. Remove K Digits
- 402. Remove K Digits
- 402.Remove K Digits
- 402. Remove K Digits
- Leetode402. Remove K Digits
- Remove K Digits
- 402. Remove K Digits
- LeetCode: Remove K Digits
- [Medium]Remove K Digits
- 402. Remove K Digits
- 402. Remove K Digits
- 402. Remove K Digits
- Remove K Digits
- Remove K Digits
- [LeetCode]Remove K Digits
- codeforces——808A——Lucky Year
- 跳表(skiplist)的代码实现
- Python Word Cloud -在anaconda中把玩一下wordcloud
- 加勒比海盗5
- 表单提交编码及相关问题
- leetcode402. Remove K Digits【单调栈变形】
- 1067. 试密码(20)
- 文章标题
- 51Nod-1136 欧拉函数【数论】
- Java内存分配全面浅析
- Profile 工具系列之四:simpleperf
- 电脑DNS修复
- NS 发送一个 cbr 数据包的过程
- codeforces——808B——Average Sleep Time