leetcode_rust/
sort_characters_by_frequency.rs

1#![allow(dead_code)]
2
3// sort the array of frequency
4pub fn frequency_sort(s: String) -> String {
5    use std::collections::HashMap;
6
7    let mut freq = HashMap::new();
8    for c in s.chars() {
9        match freq.get_mut(&c) {
10            Some(v) => {
11                *v += 1;
12            }
13            None => {
14                freq.insert(c, 1);
15            }
16        }
17    }
18
19    let mut res = String::new();
20    let mut freq = freq.iter().collect::<Vec<_>>();
21    freq.sort_by(|a, b| (*b).1.partial_cmp((*a).1).unwrap());
22
23    freq.iter().for_each(|pair| {
24        for _ in 0..*pair.1 {
25            res.push(*pair.0);
26        }
27    });
28    res
29}
30
31// add the n char of occurrences of n times to array[n]
32pub fn frequency_sort2(s: String) -> String {
33    use std::collections::HashMap;
34    use std::iter;
35
36    let mut freq = HashMap::new();
37    for c in s.chars() {
38        match freq.get_mut(&c) {
39            Some(v) => {
40                *v += 1;
41            }
42            None => {
43                freq.insert(c, 1);
44            }
45        }
46    }
47
48    let mut res = String::new();
49
50    let mut counts: Vec<String> = vec![];
51    counts.resize(s.len() + 1, String::new());
52
53    for (c, i) in freq.iter() {
54        counts[*i].push(*c);
55    }
56
57    for (i, s) in counts.iter().enumerate().rev() {
58        for c in s.chars() {
59            res.push_str(&iter::repeat(c).take(i).collect::<String>());
60        }
61    }
62    res
63}
64
65#[cfg(test)]
66mod tests {
67    use super::*;
68
69    #[test]
70    fn test1() {
71        let res = frequency_sort(String::from("tree"));
72        assert_eq!(
73            res == String::from("eert") || res == String::from("eetr"),
74            true
75        );
76    }
77
78    #[test]
79    fn test2() {
80        let res = frequency_sort2(String::from("tree"));
81        assert_eq!(
82            res == String::from("eert") || res == String::from("eetr"),
83            true
84        );
85        assert_eq!(
86            frequency_sort2(String::from("eeeee")),
87            String::from("eeeee")
88        );
89    }
90}