Created
November 22, 2021 14:08
-
-
Save wperron/af99dc902d9fe6f3c0d973e475da3163 to your computer and use it in GitHub Desktop.
Find groups of anagrams in a list of strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::collections::HashMap; | |
/// Given an array of strings, group the anagrams together in separate arrays. | |
/// An anagram is a word or phrase formed by rearranging the letters of another | |
/// word or phrase, using all the original letters exactly once. | |
/// | |
/// Example: | |
/// ``` | |
/// $ group_anagrams(["eat","tea","ten","poop","net","ate"]) | |
/// [["poop"],["net","ten"],["eat","tea","ate"]] | |
/// ``` | |
fn main() { | |
println!( | |
"{:?}", | |
group_anagrams(vec!["eat", "tea", "ten", "poop", "net", "ate"]) | |
); | |
} | |
fn group_anagrams(words: Vec<&'static str>) -> Vec<Vec<String>> { | |
let mut anagram_map: HashMap<String, Vec<String>> = HashMap::new(); | |
for word in words.into_iter() { | |
let mut sorted: Vec<char> = word.clone().chars().collect(); | |
sorted.sort_by(|a, b| b.cmp(a)); | |
let sorted = sorted.iter().collect::<String>(); | |
let val = String::from(word); | |
match anagram_map.contains_key(&sorted.clone()) { | |
true => { | |
if let Some(v) = anagram_map.get_mut(&sorted) { | |
v.push(val); | |
} | |
} | |
false => { | |
anagram_map.insert(sorted, vec![val]); | |
} | |
} | |
} | |
anagram_map.into_values().collect() | |
} | |
#[cfg(test)] | |
mod test { | |
use super::group_anagrams; | |
#[test] | |
fn test_group_anagrams() { | |
let words = vec!["foo", "bar", "baz"]; | |
let anagrams = group_anagrams(words); | |
// since there are no anagram, each string is alone in its own group. | |
assert!(anagrams.len() == 3); | |
let words = vec!["eat", "ate", "tea"]; | |
let anagrams = group_anagrams(words.clone()); | |
assert!(anagrams.len() == 1); | |
assert_eq!( | |
anagrams[0], | |
words | |
.iter() | |
.map(|&s| { String::from(s) }) | |
.collect::<Vec<String>>() | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment