mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-10 00:09:06 +01:00
27 lines
637 B
Rust
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
|
|
})
|
|
}
|
|
}
|