Skip to content

Commit

Permalink
Create: 0402-remove-k-digits.rs / .ts /.js
Browse files Browse the repository at this point in the history
  • Loading branch information
AkifhanIlgaz committed Jan 6, 2023
1 parent ee7a3bc commit d5db5dd
Show file tree
Hide file tree
Showing 3 changed files with 79 additions and 0 deletions.
26 changes: 26 additions & 0 deletions javascript/0402-remove-k-digits.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/**
* @param {string} num
* @param {number} k
* @return {string}
*/
var removeKdigits = function (num, k) {
let stack = [];
for (ch of num) {
while (k > 0 && stack.length > 0 && stack.at(-1) > ch) {
k--;
stack.pop();
}
stack.push(ch);
}

let x = 0;
while (true) {
if (stack[x] !== '0') {
break;
}
x++;
}
stack = stack.slice(x, stack.length - k);
let res = stack.join('');
return res ? res : '0';
};
32 changes: 32 additions & 0 deletions rust/0402-remove-k-digits.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
impl Solution {
pub fn remove_kdigits(num: String, k: i32) -> String {
let mut stack = vec![];
let mut k = k as usize;

for ch in num.chars() {
while let Some(&top) = stack.last() {
if k > 0 && top > ch {
k -= 1;
stack.pop();
} else {
break;
}
}

stack.push(ch);
}

// stack = stack[..stack.len() - k].to_vec();
while k != 0 {
stack.pop();
k -= 1;
}

let res: String = stack.into_iter().skip_while(|&ch| ch == '0').collect();
if res.is_empty() {
"0".to_string()
} else {
res
}
}
}
21 changes: 21 additions & 0 deletions typescript/0402-remove-k-digits.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
function removeKdigits(num: string, k: number): string {
let stack: string[] = [];
for (let ch of num) {
while (k > 0 && stack.length > 0 && stack[stack.length - 1] > ch) {
k--;
stack.pop();
}
stack.push(ch);
}

let x = 0;
while (true) {
if (stack[x] !== '0') {
break;
}
x++;
}
stack = stack.slice(x, stack.length - k);
let res = stack.join('');
return res ? res : '0';
}

0 comments on commit d5db5dd

Please sign in to comment.