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

28 lines
637 B
Rust
Raw Normal View History

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