-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.rs
73 lines (68 loc) · 2.12 KB
/
main.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
fn main() {
println!("Hello, world!");
}
struct Solution {}
impl Solution {
pub fn group_anagrams_old(strs: Vec<String>) -> Vec<Vec<String>> {
if strs.len() <= 1 { return vec![strs] }
use std::collections::HashMap;
let mut dic: HashMap<String, Vec<String>> = HashMap::new();
for os in strs { // makes ownership of strs
let mut s: Vec<char> = os.chars().collect();
s.sort();
let s: String = s.iter().collect();
dic.entry(s).and_modify(|x| x.push(os.clone())).or_insert(vec![os]);
}
dic.into_iter().fold(vec![], |mut sum, (_, vec)| {
sum.push(vec);
sum
})
}
/// an ugly O(n^2) algo
pub fn group_anagrams(strs: Vec<String>) -> Vec<Vec<String>> {
let mut strs_sorted = vec![];
for s in strs.iter() {
let mut v = s.bytes().collect::<Vec<u8>>();
v.sort();
let v = String::from_utf8(v).unwrap();
strs_sorted.push(v);
}
let mut res: Vec<Vec<String>> = vec![];
let mut idx: Vec<usize> = vec![];
for i in 0..strs.len() {
let mut found = false;
for j in 0..res.len() {
if strs_sorted[i] == strs_sorted[idx[j]] {
res[j].push(strs[i].clone());
found = true;
break;
}
}
if ! found {
res.push(vec![strs[i].clone()]);
idx.push(i);
}
}
res
}
}
#[cfg(test)]
mod test {
use crate::*;
#[test]
fn basic() {
let input = vec!["eat", "tea", "tan", "ate", "nat", "bat"];
let input: Vec<String> = input.iter().map(|x| x.to_string()).collect();
let output = vec![
vec!["ate","eat","tea"],
vec!["nat","tan"],
vec!["bat"]
];
let output: Vec<Vec<String>> = output.iter().map(|x| {
x.iter().map(|y| {
y.to_string()
}).collect()
}).collect();
assert_eq!(Solution::group_anagrams(input), output);
}
}