diff --git a/problems/sort-characters-by-frequency.rs b/problems/sort-characters-by-frequency.rs new file mode 100644 index 0000000..90774b1 --- /dev/null +++ b/problems/sort-characters-by-frequency.rs @@ -0,0 +1,18 @@ +use std::cmp::Reverse; +use std::collections::BTreeMap; + +impl Solution { + pub fn frequency_sort(s: String) -> String { + let mut freqs: BTreeMap<_, usize> = BTreeMap::new(); + + s.as_str().chars().for_each(|c| { + let current = freqs.get(&c).unwrap_or(&0); + freqs.insert(c, 1 + current); + }); + + let mut frequencies: Vec<_> = freqs.iter().collect(); + frequencies.sort_by_key(|&(_, count)| Reverse(count)); + + frequencies.iter().fold(String::new(), |s, (c, count)| s + &c.to_string().repeat(**count)) + } +}