diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 014dfa9..86ce119 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -15,3 +15,4 @@ mod p0004_median_of_two_sorted_arrays; mod p0743_network_delay_time; mod p0447_number_of_boomerangs; mod p2085_count_common_words_with_one_occurrence; +mod p2182_construct_string_with_repeat_limit; \ No newline at end of file diff --git a/src/problem/p2182_construct_string_with_repeat_limit.rs b/src/problem/p2182_construct_string_with_repeat_limit.rs new file mode 100644 index 0000000..05a9b30 --- /dev/null +++ b/src/problem/p2182_construct_string_with_repeat_limit.rs @@ -0,0 +1,69 @@ +/** + * [2182] Construct String With Repeat Limit + */ +pub struct Solution {} + + +// submission codes start here +use std::collections::BTreeMap; + +impl Solution { + pub fn repeat_limited_string(s: String, repeat_limit: i32) -> String { + let mut dict = BTreeMap::new(); + + for c in s.chars() { + let entry = dict.entry(c).or_insert(0); + *entry += 1; + } + + let mut result = Vec::new(); + + while !dict.is_empty() { + if let Some((key, mut value)) = dict.pop_last() { + let mut count = 0; + while value > 0 { + if count < repeat_limit { + result.push(key); + count += 1; + value -= 1; + } else { + match dict.last_entry() { + None => { + break; + } + Some(mut entry) => { + result.push(*entry.key()); + entry.insert(*entry.get() - 1); + + if entry.get() == &0 { + entry.remove(); + } + + count = 0; + } + } + } + } + } + } + + result.iter().collect() + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2182() { + assert_eq!(String::from("zzcccac"), Solution::repeat_limited_string( + String::from("cczazcc"), 3 + )); + assert_eq!(String::from("bbabaa"), Solution::repeat_limited_string( + String::from("aababab"), 2 + )); + } +}