rs: add «451. Sort Characters By Frequency»
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
93ef2e6198
commit
861a38fb89
1 changed files with 27 additions and 0 deletions
27
rs/2024-02-07-sort-characters-by-frequency.rs
Normal file
27
rs/2024-02-07-sort-characters-by-frequency.rs
Normal 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
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue