Skip to content

Commit

Permalink
Create: 1209-remove-all-adjacent-duplicates-in-string-II.rs / .ts
Browse files Browse the repository at this point in the history
  • Loading branch information
AkifhanIlgaz committed Jan 6, 2023
1 parent ee7a3bc commit ebeff45
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
21 changes: 21 additions & 0 deletions rust/1209-remove-all-adjacent-duplicates-in-string-II.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
impl Solution {
pub fn remove_duplicates(s: String, k: i32) -> String {
let mut stack: Vec<(char, usize)> = vec![];
for ch in s.chars() {
if !stack.is_empty() && stack.last().unwrap().0 == ch {
let mut last = stack.pop().unwrap();
last.1 += 1;
stack.push(last);
} else {
stack.push((ch, 1));
}
if stack.last().unwrap().1 == k as usize {
stack.pop();
}
}

stack.iter().fold(String::new(), |acc, &(ch, count)| {
acc + &ch.to_string().repeat(count)
})
}
}
20 changes: 20 additions & 0 deletions typescript/1209-remove-all-adjacent-duplicates-in-string-II.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
function removeDuplicates(s: string, k: number): string {
const stack: { char: string; count: number }[] = []; // [char, count];

for (const c of s) {
if (stack.length !== 0 && stack[stack.length - 1].char === c) {
stack[stack.length - 1].count++;
} else {
stack.push({ char: c, count: 1 });
}

if (stack[stack.length - 1].count === k) {
stack.pop();
}
}

return stack.reduce(
(acc, { char, count }) => (acc += char.repeat(count)),
''
);
}

0 comments on commit ebeff45

Please sign in to comment.