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

97 lines
4.5 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

> **[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/)
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
![](https://img-blog.csdnimg.cn/20210320141440557.gif)
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();
}
}
```