1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-14 01:49:41 +01:00
LeetCode/rs/2024-02-07-sort-characters-by-frequency.rs
Matej Focko 861a38fb89
rs: add «451. Sort Characters By Frequency»
Signed-off-by: Matej Focko <mfocko@redhat.com>
2024-02-08 00:18:50 +01:00

27 lines
637 B
Rust

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