Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

49. Group Anagrams

Group strings that are anagrams of each other.

HashMap with count-vector key:

#![allow(unused)]
fn main() {
// time O(n * k), space O(n * k)
pub fn group_anagrams(strs: Vec<String>) -> Vec<Vec<String>> {
    let mut map: HashMap<Vec<u8>, Vec<String>> = HashMap::with_capacity(strs.len());

    for s in strs {
        let mut vec: Vec<u8> = vec![0; 26];
        for c in s.chars() {
            vec[(c as u8 - b'a') as usize] += 1;
        }
        map.entry(vec).or_default().push(s);
    }

    map.into_values().collect()
}
}