-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy path移掉.js
More file actions
37 lines (33 loc) · 690 Bytes
/
移掉.js
File metadata and controls
37 lines (33 loc) · 690 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* @param {string} num
* @param {number} k
* @return {string}
402. 移掉 K 位数字
num = "1432219", k = 3 2 1 0
[1,2,1,9]
982 k=1
892 k=1
3044
9 k=1
9876 k=3
*/
var removeKdigits = function(num, k) {
let stack = [];
let len = num.length;
for(let i = 0; i < len; i++) {
let current = num[i];
while(k > 0 && stack.length > 0 && current < stack[stack.length - 1]) {
stack.pop();
k--;
}
stack.push(current);
}
while (k > 0) {
stack.pop();
k--
}
while(stack.length > 0 && stack[0] === '0') {
stack.shift();
}
return stack.length > 0 ? stack.join('') : '0'
};