forked from aylei/leetcode-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathn0049_group_anagrams.rs
62 lines (57 loc) · 1.34 KB
/
n0049_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
/**
* [49] Group Anagrams
*
* Given an array of strings, group anagrams together.
*
* Example:
*
*
* Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
* Output:
* [
* ["ate","eat","tea"],
* ["nat","tan"],
* ["bat"]
* ]
*
* Note:
*
*
* All inputs will be in lowercase.
* The order of your output does not matter.
*
*
*/
pub struct Solution {}
// submission codes start here
use std::collections::HashMap;
impl Solution {
pub fn group_anagrams(strs: Vec<String>) -> Vec<Vec<String>> {
let mut map = HashMap::new();
for s in strs.into_iter() {
let mut key = [0; 26];
for ch in s.chars() {
key[(ch as u32 - 'a' as u32) as usize] += 1;
}
map.entry(key).or_insert(Vec::new()).push(s);
}
map.into_iter().map(|(_, v)| v).collect()
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashSet;
// TODO: implement arbitrary match macro
#[test]
#[ignore]
fn test_49() {
assert_eq!(Solution::group_anagrams(vec_string!["eat", "tea", "tan", "ate", "nat", "bat"]),
vec![
vec_string!["tan","nat"],
vec_string!["bat"],
vec_string!["eat","ate","tea"],
]);
}
}