-
Notifications
You must be signed in to change notification settings - Fork 0
/
group_anagrams.rs
68 lines (56 loc) · 1.82 KB
/
group_anagrams.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
use std::collections::HashMap;
use std::iter::FromIterator;
/// Given an array of strings `strs`, group the anagrams together. You can return the answer in any
/// order.
///
/// An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase,
/// typically using all the original letters exactly once.
struct Solution;
impl Solution {
fn get_key(s: &str) -> String {
let mut chars: Vec<char> = s.chars().collect();
chars.sort();
String::from_iter(chars)
}
pub fn group_anagrams(strs: Vec<String>) -> Vec<Vec<String>> {
let mut groups = HashMap::new();
for s in strs {
let key = Self::get_key(&s);
groups
.entry(key)
.or_insert(Vec::new())
.push(s);
}
groups.into_values().collect()
}
}
#[cfg(test)]
mod tests {
use crate::vec_additions::VecAdditions;
use super::Solution;
#[test]
fn example_1() {
let strs = vec!["eat", "tea", "tan", "ate", "nat", "bat"];
let strs = strs.into_iter().map(|s| s.to_string()).collect();
let mut result = Solution::group_anagrams(strs);
for item in result.iter_mut() {
item.sort();
}
result.sort();
assert_eq!(result, vec![vec!["ate", "eat", "tea"], vec!["bat"], vec!["nat", "tan"]]);
}
#[test]
fn example_2() {
let strs = vec![""];
let strs = strs.into_iter().map(|s| s.to_string()).collect();
let result = Solution::group_anagrams(strs);
assert_eq!(result, vec![vec![""]]);
}
#[test]
fn example_3() {
let strs = vec!["a"];
let strs = strs.into_iter().map(|s| s.to_string()).collect();
let result = Solution::group_anagrams(strs);
assert_eq!(result, vec![vec!["a"]]);
}
}