rs: add «451. Sort Characters By Frequency»

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2024-02-08 00:18:23 +01:00
parent 93ef2e6198
commit 861a38fb89
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -0,0 +1,27 @@
use std::cmp;
use std::collections::HashMap;
impl Solution {
fn get_freqs(s: &str) -> HashMap<char, usize> {
let mut freqs = HashMap::new();
for c in s.chars() {
*freqs.entry(c).or_insert(0) += 1;
}
freqs
}
pub fn frequency_sort(mut s: String) -> String {
let mut freqs: Vec<(char, usize)> = Solution::get_freqs(&s).into_iter().collect();
freqs.sort_by_key(|(_, count)| cmp::Reverse(*count));
freqs.into_iter().fold(String::new(), |mut s, (c, n)| {
for _ in 0..n {
s.push(c);
}
s
})
}
}