File tree Expand file tree Collapse file tree 2 files changed +38
-0
lines changed Expand file tree Collapse file tree 2 files changed +38
-0
lines changed Original file line number Diff line number Diff line change 69
69
322. 零钱兑换
70
70
338. 比特位计数
71
71
392. 判断子序列
72
+ 402. 移掉 K 位数字
72
73
406. 根据身高重建队列
73
74
416. 分割等和子集
74
75
437. 路径总和
Original file line number Diff line number Diff line change
1
+ // 402. 移掉 K 位数字
2
+
3
+
4
+ /*
5
+ 单调递增栈:
6
+ 1、最小的数字就是尽可能保证高位数字更小且升序,所以要删除高位较大的数字。
7
+ 利用单调递增栈的特性,栈内元素升序,遇到比栈顶元素小的数时 栈顶元素出栈,小数入栈,这样在某一高位上就用小数替代了大数,使整体数字更小
8
+ 2、遍历数字
9
+ 1)栈不为空 且 当前数字小于栈顶数字 且 仍可移除数字,弹出栈顶数字,循环处理直到不满足条件
10
+ 2)栈不为空 或 数字不为0,则数字入栈,保证了栈底数字不为0
11
+ 3、遍历结束后如果没删够k个数字,那么继续从栈顶弹出元素,即删除低位数字
12
+ 4、从栈底弹出元素,拼凑字符串。如果字符串为空则返回"0",否则返回该字符串
13
+ */
14
+ class Solution {
15
+ public String removeKdigits (String num , int k ) {
16
+ Deque <Character > stack = new ArrayDeque <>();
17
+ for (char c : num .toCharArray ()) {
18
+ while (!stack .isEmpty () && c < stack .peek () && k > 0 ) {
19
+ stack .pop ();
20
+ k --;
21
+ }
22
+ if (c != '0' || !stack .isEmpty ()) {
23
+ stack .push (c );
24
+ }
25
+ }
26
+ StringBuffer res = new StringBuffer ();
27
+ while (!stack .isEmpty ()) {
28
+ if (k > 0 ) {
29
+ stack .pop ();
30
+ k --;
31
+ } else {
32
+ res .append (stack .pollLast ());
33
+ }
34
+ }
35
+ return res .length () == 0 ? "0" : res .toString ();
36
+ }
37
+ }
You can’t perform that action at this time.
0 commit comments