algorithm-base/animation-simulation/栈和队列/leetcode402移掉K位数字.md

97 lines
4.5 KiB
Java
Raw Normal View History

2021-03-20 08:57:12 +00:00
> **[tan45du_one](https://raw.githubusercontent.com/tan45du/tan45du.github.io/master/个人微信.15egrcgqd94w.jpg)** ,备注 github + 题目 + 问题 向我反馈
>
>
>
> <u>[****](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u> 两个平台同步,想要和题友一起刷题,互相监督的同学,可以在我的小屋点击<u>[**刷题小队**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u>进入。
#### [402. K](https://leetcode-cn.com/problems/remove-k-digits/)
2021-03-19 10:50:39 +00:00
K
###
num k 使
:
> num 10002 k
> num
1 :
> : num = "1432219", k = 3
> : "1219"
> : 4, 3, 2 1219
2 :
> : num = "10200", k = 1
> : "200"
> : 1 200.
3 :
> : num = "10", k = 2
> : "0"
> : 0
###
K
K54321321K
2021-03-20 06:19:50 +00:00
![](https://img-blog.csdnimg.cn/20210320141440557.gif)
2021-03-19 10:50:39 +00:00
PPT
> 00010 = 10 0continueK
> K224
```java
class Solution {
public String removeKdigits(String num, int k) {
//特殊情况全部删除
if (num.length() == k) {
return "0";
}
char[] s = num.toCharArray();
Stack<Character> stack = new Stack<>();
//遍历数组
for (Character i : s) {
//移除元素的情况k--
while (!stack.isEmpty() && i < stack.peek() && k > 0) {
stack.pop();
k--;
}
//栈为空且当前位为0时我们不需要将其入栈
if (stack.isEmpty() && i == '0') {
continue;
}
stack.push(i);
}
while (k > 0) {
stack.pop();
k--;
}
if (stack.isEmpty()) {
return "0";
}
//反转并返回字符串
StringBuilder str = new StringBuilder();
while (!stack.isEmpty()) {
str.append(stack.pop());
}
return str.reverse().toString();
}
}
```