From ebeff45aea3b85c781ed328849a77860af330505 Mon Sep 17 00:00:00 2001 From: AkifhanIlgaz Date: Fri, 6 Jan 2023 23:42:16 +0300 Subject: [PATCH] Create: 1209-remove-all-adjacent-duplicates-in-string-II.rs / .ts --- ...ve-all-adjacent-duplicates-in-string-II.rs | 21 +++++++++++++++++++ ...ve-all-adjacent-duplicates-in-string-II.ts | 20 ++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 rust/1209-remove-all-adjacent-duplicates-in-string-II.rs create mode 100644 typescript/1209-remove-all-adjacent-duplicates-in-string-II.ts diff --git a/rust/1209-remove-all-adjacent-duplicates-in-string-II.rs b/rust/1209-remove-all-adjacent-duplicates-in-string-II.rs new file mode 100644 index 000000000..b153a733c --- /dev/null +++ b/rust/1209-remove-all-adjacent-duplicates-in-string-II.rs @@ -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) + }) + } +} \ No newline at end of file diff --git a/typescript/1209-remove-all-adjacent-duplicates-in-string-II.ts b/typescript/1209-remove-all-adjacent-duplicates-in-string-II.ts new file mode 100644 index 000000000..88cb24bb1 --- /dev/null +++ b/typescript/1209-remove-all-adjacent-duplicates-in-string-II.ts @@ -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)), + '' + ); +}