Leetcode402. Remove K Digits
Posted wuezs
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode402. Remove K Digits相关的知识,希望对你有一定的参考价值。
题目链接:https://leetcode.com/contest/5/problems/remove-k-digits/
题目:
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 105 and will be ≥ k.
The given num does not contain any leading zero.
思路:
http://blog.csdn.net/yeqiuzs/article/details/52496818
跟这题类似,用栈实现 获取 某字符串 被删除 一些字符后 能得到的最小 最小字典序(大小)的关系。最后~~本次contest只做出这三题,
罚时80minutes
算法:
public String removeKdigits(String num, int k)
Stack<Integer> stack = new Stack<Integer>();
if (num.length() == 0 || num.length() <= k)
return "0";
for (int i = 0; i < num.length(); i++)
int cur = num.charAt(i) - '0';
while (!stack.isEmpty() && cur < stack.peek()
&& num.length() - i - 1 >= (num.length() - k) - stack.size())
stack.pop();
if (stack.size()<num.length()-k)
stack.push(cur);
StringBuilder res = new StringBuilder();
while (!stack.isEmpty())
res.insert(0, stack.pop());
while (res.length() > 0 && res.charAt(0) == '0')
res.deleteCharAt(0);
if (res.length() == 0)
return "0";
return res.toString();
以上是关于Leetcode402. Remove K Digits的主要内容,如果未能解决你的问题,请参考以下文章
[栈] leetcode 402 Remove K Digits
每日一题- Leetcode 402. Remove K Digits