feat: 1209_remove_all_adjacent_duplicates_in_string_2

This commit is contained in:
SquidSpirit 2025-09-20 03:05:51 +08:00
parent b69b2b25a9
commit 90bcaf5436
3 changed files with 45 additions and 0 deletions

View File

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "remove_all_adjacent_duplicates_in_string_2"
version = "0.1.0"

View File

@ -0,0 +1,6 @@
[package]
name = "remove_all_adjacent_duplicates_in_string_2"
version = "0.1.0"
edition = "2024"
[dependencies]

View File

@ -0,0 +1,32 @@
pub struct Solution;
impl Solution {
pub fn remove_duplicates(s: String, k: i32) -> String {
let mut stack = String::new();
let mut dup_count_stack = Vec::<i32>::new();
let mut dup_count = 1;
for c in s.bytes() {
if stack.is_empty() {
stack.push(c as char);
} else if c == stack.bytes().last().unwrap() {
dup_count += 1;
if dup_count == k {
while dup_count > 1 {
stack.pop();
dup_count -= 1;
}
dup_count = dup_count_stack.pop().unwrap_or(1);
} else {
stack.push(c as char);
}
} else {
stack.push(c as char);
dup_count_stack.push(dup_count);
dup_count = 1;
}
}
stack
}
}