20240113 Finished

This commit is contained in:
jackfiled 2024-01-13 13:22:34 +08:00
parent e2e9269ec2
commit d73d1ab43a
2 changed files with 70 additions and 0 deletions

View File

@ -15,3 +15,4 @@ mod p0004_median_of_two_sorted_arrays;
mod p0743_network_delay_time; mod p0743_network_delay_time;
mod p0447_number_of_boomerangs; mod p0447_number_of_boomerangs;
mod p2085_count_common_words_with_one_occurrence; mod p2085_count_common_words_with_one_occurrence;
mod p2182_construct_string_with_repeat_limit;

View File

@ -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
));
}
}