leetcode_rust/
group_anagrams.rs

1#![allow(dead_code)]
2
3// Sort all strings and then record their index in hash map
4pub fn group_anagrams(strs: Vec<String>) -> Vec<Vec<String>> {
5    use std::collections::HashMap;
6
7    let mut map = HashMap::new();
8    let mut res = vec![];
9    let sorted_strs: Vec<Vec<u8>> = strs
10        .iter()
11        .map(|s| {
12            let mut s = s.clone().into_bytes();
13            s.sort();
14            s
15        })
16        .collect();
17
18    for i in 0..strs.len() {
19        let temp = sorted_strs[i].clone();
20        match map.get(&temp) {
21            None => {
22                res.push(vec![]);
23                map.insert(temp.clone(), res.len() - 1);
24            }
25            Some(_) => {}
26        }
27        let index = map.get(&temp).unwrap();
28        res[*index].push(strs[i].clone());
29    }
30
31    res
32}
33
34// ref other people's method
35pub fn group_anagrams2(strs: Vec<String>) -> Vec<Vec<String>> {
36    use std::collections::HashMap;
37
38    strs.into_iter()
39        .fold(HashMap::new(), |mut map, s| {
40            map.entry(s.bytes().fold([0; 26], |mut hash, b| {
41                hash[(b - b'a') as usize] += 1u8;
42                hash
43            }))
44                .or_insert(vec![])
45                .push(s);
46            map
47        })
48        .into_iter()
49        .map(|s| s.1)
50        .collect()
51}
52
53#[cfg(test)]
54mod tests {
55    use super::*;
56
57    #[test]
58    fn test1() {
59        let strs = vec![
60            "eat".to_string(),
61            "tea".to_string(),
62            "tan".to_string(),
63            "ate".to_string(),
64            "nat".to_string(),
65            "bat".to_string(),
66        ];
67
68        let res = group_anagrams(strs);
69
70        assert_eq!(
71            res,
72            vec![vec!["eat", "tea", "ate"], vec!["tan", "nat"], vec!["bat"]]
73        )
74    }
75}