diff --git a/1209_remove_all_adjacent_duplicates_in_string_2/Cargo.lock b/1209_remove_all_adjacent_duplicates_in_string_2/Cargo.lock new file mode 100644 index 0000000..d43fbd4 --- /dev/null +++ b/1209_remove_all_adjacent_duplicates_in_string_2/Cargo.lock @@ -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" diff --git a/1209_remove_all_adjacent_duplicates_in_string_2/Cargo.toml b/1209_remove_all_adjacent_duplicates_in_string_2/Cargo.toml new file mode 100644 index 0000000..42b9b59 --- /dev/null +++ b/1209_remove_all_adjacent_duplicates_in_string_2/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "remove_all_adjacent_duplicates_in_string_2" +version = "0.1.0" +edition = "2024" + +[dependencies] diff --git a/1209_remove_all_adjacent_duplicates_in_string_2/src/lib.rs b/1209_remove_all_adjacent_duplicates_in_string_2/src/lib.rs new file mode 100644 index 0000000..721c3f0 --- /dev/null +++ b/1209_remove_all_adjacent_duplicates_in_string_2/src/lib.rs @@ -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::::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 + } +}