I have written a code snippet to use HashMap<String, Vec<&String>> as the main data structure, and finally, I want to return a collected Vec<Vec<String>>, I can archive it by a for-loop, it there any pure iterator way to do this? (I have tried several times, but got tons of
confused compiler errors)
pub fn group_anagrams(strs: Vec<String>) -> Vec<Vec<String>> {
let mut map: HashMap<String, Vec<&String>> = HashMap::new();
for s in &strs {
let mut key = s.clone();
unsafe {
key.as_bytes_mut().sort();
}
(*map.entry(key).or_insert(vec![])).push(s);
}
let mut ans: Vec<Vec<String>> = Vec::new();
// I don't like these 2 lines
for v in map.values() {
ans.push(v.iter().cloned().cloned().collect::<Vec<String>>())
}
ans
}
I also tried with this code:
pub fn group_anagrams(strs: Vec<String>) -> Vec<Vec<String>> {
let mut map: HashMap<String, Vec<String>> = HashMap::new();
for s in strs {
let mut key = s.clone();
unsafe {
key.as_bytes_mut().sort();
}
(*map.entry(key).or_insert(vec![])).push(s);
}
map.values().cloned().collect::<Vec<Vec<String>>>()
}
In the last line, I want to move all the values from hashmap into result vector but also failed because of the lifetime error(then I gave up with a cloned vector), I am wondering how to make it.