-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.rs
105 lines (79 loc) · 2.74 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// https://leetcode.com/problems/group-anagrams/
pub struct Solution;
impl Solution {
pub fn group_anagrams(strs: Vec<String>) -> Vec<Vec<String>> {
use std::collections::{BTreeMap, HashMap};
let mut res: HashMap<BTreeMap<char, u8>, Vec<String>> = HashMap::new();
strs.into_iter().for_each(|word| {
let mut key: BTreeMap<char, u8> = BTreeMap::new();
for ch in word.chars() {
key.entry(ch).and_modify(|count| *count += 1).or_insert(1);
}
res.entry(key).or_default().push(word);
});
res.into_values().collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashSet;
#[test]
fn example1() {
let strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
.into_iter()
.map(String::from)
.collect::<Vec<_>>();
let res = Solution::group_anagrams(strs);
let res = res
.into_iter()
.map(|group| group.into_iter().collect::<HashSet<_>>())
.collect::<Vec<_>>();
let target = [
["bat"].to_vec(),
["nat", "tan"].to_vec(),
["ate", "eat", "tea"].to_vec(),
]
.into_iter()
.map(|group| group.into_iter().map(String::from).collect::<HashSet<_>>())
.collect::<Vec<_>>();
assert_eq!(res.len(), target.len());
target.iter().for_each(|group| {
assert!(res.contains(group));
});
}
#[test]
fn example2() {
let strs = [""].into_iter().map(String::from).collect::<Vec<_>>();
let res = Solution::group_anagrams(strs);
let res = res
.into_iter()
.map(|group| group.into_iter().collect::<HashSet<_>>())
.collect::<Vec<_>>();
let target = [[""].to_vec()]
.into_iter()
.map(|group| group.into_iter().map(String::from).collect::<HashSet<_>>())
.collect::<Vec<_>>();
assert_eq!(res.len(), target.len());
target.iter().for_each(|group| {
assert!(res.contains(group));
});
}
#[test]
fn example3() {
let strs = ["a"].into_iter().map(String::from).collect::<Vec<_>>();
let res = Solution::group_anagrams(strs);
let res = res
.into_iter()
.map(|group| group.into_iter().collect::<HashSet<_>>())
.collect::<Vec<_>>();
let target = [["a"].to_vec()]
.into_iter()
.map(|group| group.into_iter().map(String::from).collect::<HashSet<_>>())
.collect::<Vec<_>>();
assert_eq!(res.len(), target.len());
target.iter().for_each(|group| {
assert!(res.contains(group));
});
}
}