-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths0049_group_anagrams.rs
More file actions
59 lines (52 loc) · 1.79 KB
/
s0049_group_anagrams.rs
File metadata and controls
59 lines (52 loc) · 1.79 KB
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
#![allow(unused)]
pub struct Solution {}
use std::collections::HashMap;
impl Solution {
// Time Complexity: O(NKlogK), where N is the length of strs, and K is the maximum
// length of a string in strs. The outer loop has complexity O(N) as we iterate
// through each string. Then, we sort each string in O(KlogK) time.
// Space Complexity: O(NK), the total information content stored in ans.
pub fn group_anagrams(strs: Vec<String>) -> Vec<Vec<String>> {
// K: sorted(chars) V : Vec<String>
let mut ans = HashMap::new();
for word in strs.iter() {
let mut chs = word.chars().collect::<Vec<char>>();
chs.sort();
let val = ans.entry(chs).or_insert(vec![]);
val.push(word.to_string());
}
ans.into_iter()
.map(|(_, vals)| vals)
.collect::<Vec<Vec<String>>>()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_49() {
// assert_eq!(
// Solution::group_anagrams(vec![
// "eat".to_string(),
// "tea".to_string(),
// "tan".to_string(),
// "ate".to_string(),
// "nat".to_string(),
// "bat".to_string(),
// ]),
// vec![
// vec!["bat".to_string(),],
// vec!["nat".to_string(), "tan".to_string(),],
// vec!["ate".to_string(), "eat".to_string(), "tea".to_string(),]
// ]
// );
// assert_eq!(
// Solution::group_anagrams(vec!["".to_string(),]),
// vec![vec!["".to_string(),]]
// );
// assert_eq!(
// Solution::group_anagrams(vec!["a".to_string(),]),
// vec![vec!["a".to_string(),]]
// );
}
}