Skip to content

Commit d5db5dd

Browse files
committed
Create: 0402-remove-k-digits.rs / .ts /.js
1 parent ee7a3bc commit d5db5dd

File tree

3 files changed

+79
-0
lines changed

3 files changed

+79
-0
lines changed

Diff for: javascript/0402-remove-k-digits.js

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* @param {string} num
3+
* @param {number} k
4+
* @return {string}
5+
*/
6+
var removeKdigits = function (num, k) {
7+
let stack = [];
8+
for (ch of num) {
9+
while (k > 0 && stack.length > 0 && stack.at(-1) > ch) {
10+
k--;
11+
stack.pop();
12+
}
13+
stack.push(ch);
14+
}
15+
16+
let x = 0;
17+
while (true) {
18+
if (stack[x] !== '0') {
19+
break;
20+
}
21+
x++;
22+
}
23+
stack = stack.slice(x, stack.length - k);
24+
let res = stack.join('');
25+
return res ? res : '0';
26+
};

Diff for: rust/0402-remove-k-digits.rs

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
impl Solution {
2+
pub fn remove_kdigits(num: String, k: i32) -> String {
3+
let mut stack = vec![];
4+
let mut k = k as usize;
5+
6+
for ch in num.chars() {
7+
while let Some(&top) = stack.last() {
8+
if k > 0 && top > ch {
9+
k -= 1;
10+
stack.pop();
11+
} else {
12+
break;
13+
}
14+
}
15+
16+
stack.push(ch);
17+
}
18+
19+
// stack = stack[..stack.len() - k].to_vec();
20+
while k != 0 {
21+
stack.pop();
22+
k -= 1;
23+
}
24+
25+
let res: String = stack.into_iter().skip_while(|&ch| ch == '0').collect();
26+
if res.is_empty() {
27+
"0".to_string()
28+
} else {
29+
res
30+
}
31+
}
32+
}

Diff for: typescript/0402-remove-k-digits.ts

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
function removeKdigits(num: string, k: number): string {
2+
let stack: string[] = [];
3+
for (let ch of num) {
4+
while (k > 0 && stack.length > 0 && stack[stack.length - 1] > ch) {
5+
k--;
6+
stack.pop();
7+
}
8+
stack.push(ch);
9+
}
10+
11+
let x = 0;
12+
while (true) {
13+
if (stack[x] !== '0') {
14+
break;
15+
}
16+
x++;
17+
}
18+
stack = stack.slice(x, stack.length - k);
19+
let res = stack.join('');
20+
return res ? res : '0';
21+
}

0 commit comments

Comments
 (0)